From 2c3954442a0b5b33af1564aaa3c5b8eb51ac918f Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 8 Oct 2026 00:34:14 +0000 Subject: [PATCH 1/2] Use `link[T]` in place of `*Node` in syntax nodes. --- tools/customlint/forbidparentaccess.go | 4 +- .../transformers/tstransforms/parentaccess.go | 6 + .../tstransforms/parentaccess.go.golden | 8 + tools/scripts/tsc/ast.json | 134 +- tools/scripts/tsc/ast.schema.json | 4 - tools/scripts/tsc/generate-encoder.ts | 2 + tools/scripts/tsc/generate-go-ast.ts | 136 +- tools/scripts/tsc/schema.ts | 24 +- tsc/internal/api/encoder/decoder_test.go | 168 +- tsc/internal/api/encoder/encoder_generated.go | 310 +- tsc/internal/ast/arena.go | 262 + tsc/internal/ast/arena_test.go | 125 + tsc/internal/ast/ast.go | 1074 ++-- tsc/internal/ast/ast_generated.go | 4935 ++++++++++------- tsc/internal/ast/functionflags.go | 4 +- tsc/internal/ast/parseoptions.go | 2 +- tsc/internal/ast/precedence.go | 12 +- tsc/internal/ast/utilities.go | 555 +- tsc/internal/binder/binder.go | 341 +- tsc/internal/binder/nameresolver.go | 50 +- tsc/internal/binder/referenceresolver.go | 12 +- tsc/internal/checker/checker.go | 1576 +++--- tsc/internal/checker/checker_test.go | 6 +- tsc/internal/checker/emitresolver.go | 26 +- tsc/internal/checker/emitsupport.go | 62 +- tsc/internal/checker/flow.go | 208 +- tsc/internal/checker/grammarchecks.go | 352 +- tsc/internal/checker/inference.go | 4 +- tsc/internal/checker/jsdoc.go | 10 +- tsc/internal/checker/jsx.go | 54 +- tsc/internal/checker/nodebuilder.go | 6 +- tsc/internal/checker/nodebuilder_hover.go | 14 +- tsc/internal/checker/nodebuilderimpl.go | 120 +- tsc/internal/checker/nodebuilderscopes.go | 15 +- tsc/internal/checker/nodecopy.go | 122 +- tsc/internal/checker/pseudotypenodebuilder.go | 60 +- tsc/internal/checker/relater.go | 26 +- tsc/internal/checker/services.go | 96 +- tsc/internal/checker/symbolaccessibility.go | 30 +- tsc/internal/checker/utilities.go | 156 +- tsc/internal/compiler/fileloader.go | 26 +- tsc/internal/compiler/includeprocessor.go | 6 +- tsc/internal/compiler/program.go | 24 +- tsc/internal/compiler/program_test.go | 4 +- tsc/internal/core/arena.go | 16 +- tsc/internal/evaluator/evaluator.go | 16 +- .../execute/incremental/programtosnapshot.go | 2 +- tsc/internal/format/api.go | 2 +- tsc/internal/format/indent.go | 40 +- tsc/internal/format/rulecontext.go | 8 +- tsc/internal/format/scanner.go | 10 +- tsc/internal/format/span.go | 6 +- tsc/internal/format/util.go | 10 +- tsc/internal/linkarena/heap_linux.go | 31 + tsc/internal/linkarena/heap_other.go | 5 + tsc/internal/linkarena/linkarena.go | 444 ++ tsc/internal/linkarena/linkarena_test.go | 284 + tsc/internal/linkarena/norace_test.go | 5 + tsc/internal/linkarena/race_test.go | 5 + tsc/internal/linkarena/verify.go | 212 + tsc/internal/ls/autoimport/extract.go | 10 +- tsc/internal/ls/autoimport/fix.go | 92 +- tsc/internal/ls/autoimport/import_adder.go | 14 +- tsc/internal/ls/autoinsert.go | 30 +- tsc/internal/ls/callhierarchy.go | 66 +- tsc/internal/ls/change/delete.go | 34 +- tsc/internal/ls/change/tracker.go | 22 +- .../codeactions_fixmissingtypeannotation.go | 108 +- tsc/internal/ls/codeactions_importfixes.go | 4 +- .../ls/codeactions_missingmemberfixer.go | 22 +- tsc/internal/ls/codelens.go | 6 +- tsc/internal/ls/completions.go | 398 +- tsc/internal/ls/definition.go | 36 +- tsc/internal/ls/documenthighlights.go | 76 +- tsc/internal/ls/file_rename.go | 24 +- tsc/internal/ls/findallreferences.go | 186 +- tsc/internal/ls/folding.go | 64 +- tsc/internal/ls/format.go | 2 +- tsc/internal/ls/hover.go | 72 +- tsc/internal/ls/importTracker.go | 50 +- tsc/internal/ls/inlay_hints.go | 84 +- tsc/internal/ls/jsdoc.go | 52 +- tsc/internal/ls/jsdoc_snippet.go | 28 +- tsc/internal/ls/linkedediting.go | 18 +- tsc/internal/ls/lsutil/asi.go | 2 +- tsc/internal/ls/lsutil/completednode.go | 28 +- tsc/internal/ls/lsutil/organizeimports.go | 34 +- tsc/internal/ls/lsutil/symbol_display.go | 4 +- tsc/internal/ls/lsutil/utilities.go | 2 +- tsc/internal/ls/organizeimports.go | 130 +- tsc/internal/ls/rename.go | 16 +- tsc/internal/ls/selectionranges.go | 10 +- tsc/internal/ls/semantictokens.go | 22 +- tsc/internal/ls/signaturehelp.go | 60 +- tsc/internal/ls/sourcedefinition.go | 24 +- tsc/internal/ls/string_completions.go | 46 +- tsc/internal/ls/symbols.go | 20 +- tsc/internal/ls/utilities.go | 194 +- tsc/internal/modulespecifiers/specifiers.go | 2 +- tsc/internal/parser/jsdoc.go | 31 +- tsc/internal/parser/parser.go | 108 +- tsc/internal/parser/parser_test.go | 34 +- tsc/internal/parser/reparser.go | 155 +- tsc/internal/printer/changetrackerwriter.go | 2 +- tsc/internal/printer/emitcontext.go | 26 +- tsc/internal/printer/factory.go | 24 +- tsc/internal/printer/printer.go | 908 +-- tsc/internal/printer/printer_test.go | 4 +- tsc/internal/printer/utilities.go | 48 +- tsc/internal/pseudochecker/lookup.go | 112 +- tsc/internal/scanner/scanner.go | 10 +- tsc/internal/scanner/scanner_test.go | 9 +- tsc/internal/scanner/utilities.go | 2 +- tsc/internal/testrunner/compiler_runner.go | 14 +- .../tsbaseline/type_symbol_baseline.go | 44 +- .../transformers/declarations/diagnostics.go | 42 +- .../transformers/declarations/tracker.go | 6 +- .../transformers/declarations/transform.go | 359 +- .../transformers/declarations/util.go | 6 +- tsc/internal/transformers/destructuring.go | 14 +- .../transformers/estransforms/async.go | 104 +- .../transformers/estransforms/classfields.go | 262 +- .../transformers/estransforms/classthis.go | 12 +- .../transformers/estransforms/esdecorator.go | 206 +- .../estransforms/exponentiation.go | 14 +- .../transformers/estransforms/forawait.go | 66 +- .../estransforms/logicalassignment.go | 12 +- .../estransforms/namedevaluation.go | 52 +- .../estransforms/nullishcoalescing.go | 6 +- .../estransforms/objectrestspread.go | 82 +- .../estransforms/optionalcatch.go | 4 +- .../estransforms/optionalchain.go | 26 +- .../estransforms/taggedtemplate.go | 22 +- .../transformers/estransforms/using.go | 54 +- .../transformers/estransforms/utilities.go | 24 +- .../transformers/jsxtransforms/jsx.go | 36 +- .../moduletransforms/commonjsmodule.go | 266 +- .../transformers/moduletransforms/esmodule.go | 42 +- .../moduletransforms/externalmoduleinfo.go | 32 +- .../moduletransforms/utilities.go | 6 +- .../tstransforms/importelision.go | 18 +- .../tstransforms/legacydecorators.go | 60 +- .../transformers/tstransforms/metadata.go | 52 +- .../tstransforms/runtimesyntax.go | 100 +- .../transformers/tstransforms/typeeraser.go | 90 +- .../tstransforms/typeserializer.go | 56 +- tsc/internal/transformers/utilities.go | 52 +- tsc/internal/tsoptions/tsconfigparsing.go | 42 +- 148 files changed, 10413 insertions(+), 7702 deletions(-) create mode 100644 tsc/internal/ast/arena.go create mode 100644 tsc/internal/ast/arena_test.go create mode 100644 tsc/internal/linkarena/heap_linux.go create mode 100644 tsc/internal/linkarena/heap_other.go create mode 100644 tsc/internal/linkarena/linkarena.go create mode 100644 tsc/internal/linkarena/linkarena_test.go create mode 100644 tsc/internal/linkarena/norace_test.go create mode 100644 tsc/internal/linkarena/race_test.go create mode 100644 tsc/internal/linkarena/verify.go diff --git a/tools/customlint/forbidparentaccess.go b/tools/customlint/forbidparentaccess.go index a4088b5583585..09a96a9d3f8e8 100644 --- a/tools/customlint/forbidparentaccess.go +++ b/tools/customlint/forbidparentaccess.go @@ -11,7 +11,7 @@ import ( var forbidParentAccessAnalyzer = &analysis.Analyzer{ Name: "forbidparentaccess", - Doc: "forbids .Parent access in internal/transformers except internal/transformers/declarations", + Doc: "forbids .Parent and .SetParent access in internal/transformers except internal/transformers/declarations", Requires: []*analysis.Analyzer{ inspect.Analyzer, }, @@ -23,7 +23,7 @@ var forbidParentAccessAnalyzer = &analysis.Analyzer{ in := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) for c := range in.Root().Preorder((*ast.SelectorExpr)(nil)) { n := c.Node().(*ast.SelectorExpr) - if n.Sel.Name != "Parent" { + if n.Sel.Name != "Parent" && n.Sel.Name != "SetParent" { continue } diff --git a/tools/customlint/testdata/parentaccess/internal/transformers/tstransforms/parentaccess.go b/tools/customlint/testdata/parentaccess/internal/transformers/tstransforms/parentaccess.go index 2297a515042ad..a69712dbc4ef9 100644 --- a/tools/customlint/testdata/parentaccess/internal/transformers/tstransforms/parentaccess.go +++ b/tools/customlint/testdata/parentaccess/internal/transformers/tstransforms/parentaccess.go @@ -6,6 +6,8 @@ func (n *Node) Parent() *Node { return nil } +func (n *Node) SetParent(parent *Node) {} + type WithField struct { Parent *Node } @@ -17,3 +19,7 @@ func badCall(n *Node) { func badFieldAccess(w *WithField) { _ = w.Parent } + +func badSet(n *Node) { + n.SetParent(nil) +} diff --git a/tools/customlint/testdata/parentaccess/internal/transformers/tstransforms/parentaccess.go.golden b/tools/customlint/testdata/parentaccess/internal/transformers/tstransforms/parentaccess.go.golden index f04842bfd5f29..f47c6798c5123 100644 --- a/tools/customlint/testdata/parentaccess/internal/transformers/tstransforms/parentaccess.go.golden +++ b/tools/customlint/testdata/parentaccess/internal/transformers/tstransforms/parentaccess.go.golden @@ -6,6 +6,8 @@ return nil } + func (n *Node) SetParent(parent *Node) {} + type WithField struct { Parent *Node } @@ -22,3 +24,9 @@ !!! forbidparentaccess: Transformers are run on nodes with potentially unset .Parent pointers, do not use them in transformers. Track context in the transform itself, instead. } + func badSet(n *Node) { + n.SetParent(nil) + ~~~~~~~~~ +!!! forbidparentaccess: Transformers are run on nodes with potentially unset .Parent pointers, do not use them in transformers. Track context in the transform itself, instead. + } + diff --git a/tools/scripts/tsc/ast.json b/tools/scripts/tsc/ast.json index a133915a10665..7b98f92210d05 100644 --- a/tools/scripts/tsc/ast.json +++ b/tools/scripts/tsc/ast.json @@ -1191,7 +1191,6 @@ "inherited": true } ], - "arena": true, "instantiationAliases": { "EndOfFile": "EndOfFile", "DotToken": "DotToken", @@ -1238,8 +1237,7 @@ "name": "Text", "type": "string" } - ], - "arena": true + ] }, "PrivateIdentifier": { "extends": [ @@ -1322,8 +1320,7 @@ "optional": true, "visit": "embeddedStatement" } - ], - "arena": true + ] }, "DoStatement": { "generateSubtreeFacts": true, @@ -1464,8 +1461,7 @@ "type": "Expression", "optional": true } - ], - "arena": true + ] }, "WithStatement": { "generateSubtreeFacts": true, @@ -1634,8 +1630,7 @@ "name": "Expression", "type": "Expression" } - ], - "arena": true + ] }, "Block": { "generateSubtreeFacts": true, @@ -1654,8 +1649,7 @@ "name": "MultiLine", "type": "bool" } - ], - "arena": true + ] }, "VariableStatement": { "extends": [ @@ -1672,8 +1666,7 @@ "name": "DeclarationList", "type": "VariableDeclarationList" } - ], - "arena": true + ] }, "VariableDeclaration": { "extends": [ @@ -1703,8 +1696,7 @@ "type": "Expression", "optional": true } - ], - "arena": true + ] }, "VariableDeclarationList": { "extends": [ @@ -1721,8 +1713,7 @@ "name": "Flags", "inherited": true } - ], - "arena": true + ] }, "BindingPattern": { "extends": [ @@ -1783,8 +1774,7 @@ "type": "Expression", "optional": true } - ], - "arena": true + ] }, "BindingElement": { "extends": [ @@ -1885,8 +1875,7 @@ "type": "*FlowNode", "goOnly": true } - ], - "arena": true + ] }, "ClassDeclaration": { "extends": [ @@ -1964,8 +1953,7 @@ "type": "HeritageClauseElement", "list": "NodeList" } - ], - "arena": true + ] }, "InterfaceDeclaration": { "extends": [ @@ -2002,8 +1990,7 @@ "type": "TypeElement", "list": "NodeList" } - ], - "arena": true + ] }, "TypeAliasDeclaration": { "kind": [ @@ -2038,8 +2025,7 @@ "name": "Type", "type": "TypeNode" } - ], - "arena": true + ] }, "EnumMember": { "extends": [ @@ -2327,8 +2313,7 @@ "name": "Type", "inherited": true } - ], - "arena": true + ] }, "ConstructorDeclaration": { "kind": "Constructor", @@ -2521,8 +2506,7 @@ "name": "Type", "inherited": true } - ], - "arena": true + ] }, "MethodDeclaration": { "extends": [ @@ -2609,8 +2593,7 @@ "name": "Initializer", "type": "Expression" } - ], - "arena": true + ] }, "PropertyDeclaration": { "extends": [ @@ -2701,7 +2684,6 @@ "inherited": true } ], - "arena": true, "instantiationAliases": { "NullLiteral": "NullKeyword", "TrueLiteral": "TrueKeyword", @@ -2725,8 +2707,7 @@ "inherited": true, "bitmask": "TokenFlagsStringLiteralFlags" } - ], - "arena": true + ] }, "NumericLiteral": { "extends": [ @@ -2742,8 +2723,7 @@ "inherited": true, "bitmask": "TokenFlagsNumericLiteralFlags" } - ], - "arena": true + ] }, "BigIntLiteral": { "extends": [ @@ -2824,8 +2804,7 @@ "name": "Right", "type": "Expression" } - ], - "arena": true + ] }, "PrefixUnaryExpression": { "generateSubtreeFacts": true, @@ -2848,8 +2827,7 @@ "name": "Operand", "type": "Expression" } - ], - "arena": true + ] }, "PostfixUnaryExpression": { "generateSubtreeFacts": true, @@ -3045,8 +3023,7 @@ "name": "WhenFalse", "type": "Expression" } - ], - "arena": true + ] }, "PropertyAccessExpression": { "extends": [ @@ -3074,8 +3051,7 @@ "inherited": true, "bitmask": "NodeFlagsOptionalChain" } - ], - "arena": true + ] }, "ElementAccessExpression": { "generateSubtreeFacts": true, @@ -3103,8 +3079,7 @@ "inherited": true, "bitmask": "NodeFlagsOptionalChain" } - ], - "arena": true + ] }, "CallExpression": { "extends": [ @@ -3138,8 +3113,7 @@ "inherited": true, "bitmask": "NodeFlagsOptionalChain" } - ], - "arena": true + ] }, "NewExpression": { "extends": [ @@ -3288,8 +3262,7 @@ "name": "Expression", "type": "Expression" } - ], - "arena": true + ] }, "ArrayLiteralExpression": { "generateSubtreeFacts": true, @@ -3370,8 +3343,7 @@ "name": "Initializer", "type": "Expression" } - ], - "arena": true + ] }, "ShorthandPropertyAssignment": { "extends": [ @@ -3490,8 +3462,7 @@ "type": "TKind", "inherited": true } - ], - "arena": true + ] }, "UnionTypeNode": { "kind": "UnionType", @@ -3503,8 +3474,7 @@ "name": "Types", "inherited": true } - ], - "arena": true + ] }, "IntersectionTypeNode": { "kind": "IntersectionType", @@ -3516,8 +3486,7 @@ "name": "Types", "inherited": true } - ], - "arena": true + ] }, "ConditionalTypeNode": { "kind": "ConditionalType", @@ -3562,8 +3531,7 @@ "name": "Type", "type": "TypeNode" } - ], - "arena": true + ] }, "InferTypeNode": { "kind": "InferType", @@ -3587,8 +3555,7 @@ "name": "ElementType", "type": "TypeNode" } - ], - "arena": true + ] }, "IndexedAccessTypeNode": { "kind": "IndexedAccessType", @@ -3604,8 +3571,7 @@ "name": "IndexType", "type": "TypeNode" } - ], - "arena": true + ] }, "TypeReferenceNode": { "kind": "TypeReference", @@ -3621,8 +3587,7 @@ "name": "TypeArguments", "inherited": true } - ], - "arena": true + ] }, "ExpressionWithTypeArguments": { "extends": [ @@ -3640,8 +3605,7 @@ "optional": true, "list": "NodeList" } - ], - "arena": true + ] }, "LiteralTypeNode": { "kind": "LiteralType", @@ -3653,8 +3617,7 @@ "name": "Literal", "type": "Node" } - ], - "arena": true + ] }, "ThisTypeNode": { "kind": "ThisType", @@ -3805,8 +3768,7 @@ "type": "TypeElement", "list": "NodeList" } - ], - "arena": true + ] }, "TupleTypeNode": { "kind": "TupleType", @@ -3882,8 +3844,7 @@ "name": "Type", "type": "TypeNode" } - ], - "arena": true + ] }, "FunctionTypeNode": { "kind": "FunctionType", @@ -3903,8 +3864,7 @@ "name": "Type", "inherited": true } - ], - "arena": true + ] }, "ConstructorTypeNode": { "kind": "ConstructorType", @@ -4287,8 +4247,7 @@ "list": "NodeList", "optional": true } - ], - "arena": true + ] }, "JSDocTypeExpression": { "extends": [ @@ -4382,8 +4341,7 @@ "name": "Comment", "inherited": true } - ], - "arena": true + ] }, "JSDocTemplateTag": { "extends": [ @@ -4517,8 +4475,7 @@ "name": "Comment", "inherited": true } - ], - "arena": true + ] }, "JSDocSeeTag": { "extends": [ @@ -4966,8 +4923,7 @@ "type": "Identifier", "private": true } - ], - "arena": true + ] }, "JSDocText": { "extends": [ @@ -4978,8 +4934,7 @@ "name": "text", "inherited": true } - ], - "arena": true + ] }, "JSDocLink": { "extends": [ @@ -5065,8 +5020,7 @@ "type": "TypeNode", "optional": true } - ], - "arena": true + ] }, "SyntheticReferenceExpression": { "generateSubtreeFacts": true, diff --git a/tools/scripts/tsc/ast.schema.json b/tools/scripts/tsc/ast.schema.json index ae08f0ac65a8a..3298f6d1b970b 100644 --- a/tools/scripts/tsc/ast.schema.json +++ b/tools/scripts/tsc/ast.schema.json @@ -290,10 +290,6 @@ "$ref": "#/definitions/member" } }, - "arena": { - "type": "boolean", - "description": "Whether this node uses an object arena for allocation." - }, "handWrittenVisitor": { "type": "boolean", "description": "Whether this node's ForEachChild and VisitEachChild functions are hand-written rather than generated." diff --git a/tools/scripts/tsc/generate-encoder.ts b/tools/scripts/tsc/generate-encoder.ts index 1b106bb8ff555..60618aca33ad3 100644 --- a/tools/scripts/tsc/generate-encoder.ts +++ b/tools/scripts/tsc/generate-encoder.ts @@ -231,6 +231,8 @@ function goParamName(m: MemberInfo): string { /** Get the Go accessor for a member on a cast struct (e.g., "n.IsTypeOnly", "n.Name()"). */ function goFieldAccess(m: MemberInfo): string { if (m.private) return `n.${api.capitalize(m.name)}()`; + // Links to nodes and node lists are read through accessors. + if (m.goLinkTarget()) return `n.${m.name}()`; return `n.${m.name}`; } diff --git a/tools/scripts/tsc/generate-go-ast.ts b/tools/scripts/tsc/generate-go-ast.ts index c2c7ca98a2570..14e2846a24f0d 100644 --- a/tools/scripts/tsc/generate-go-ast.ts +++ b/tools/scripts/tsc/generate-go-ast.ts @@ -91,18 +91,6 @@ class CodeWriter { } function generateNodeFactoryStruct(w: CodeWriter) { - const arenaFields: { fieldName: string; typeName: string; }[] = []; - for (const node of api.nodes()) { - if (!node.arena) continue; - arenaFields.push({ - fieldName: `${api.uncapitalize(node.name)}Arena`, - typeName: node.name, - }); - } - arenaFields.push({ fieldName: "modifierListArena", typeName: "ModifierList" }); - arenaFields.push({ fieldName: "nodeListArena", typeName: "NodeList" }); - arenaFields.sort((a, b) => a.fieldName.localeCompare(b.fieldName)); - w.write("// ──────────────────────────────────────────────────────────────────────"); w.write("// NodeFactory"); w.write("// ──────────────────────────────────────────────────────────────────────"); @@ -110,9 +98,9 @@ function generateNodeFactoryStruct(w: CodeWriter) { w.write("type NodeFactory struct {"); w.push(); w.write("hooks NodeFactoryHooks"); - for (const { fieldName, typeName } of arenaFields) { - w.write(`${fieldName} core.Arena[${typeName}]`); - } + w.write("arena *linkarena.Arena // memory of the nodes the factory creates; see arena.go"); + w.write("parsing bool // every node handed to the factory was created by it"); + w.write("sourceText string // text whose substrings the arena keeps alive as a whole"); w.write(""); w.write("nodeCount int"); w.write("textCount int"); @@ -121,6 +109,51 @@ function generateNodeFactoryStruct(w: CodeWriter) { w.write(""); } +// ── Links ────────────────────────────────────────────────────────────────── + +// Nodes live in arena memory and refer to each other through 4-byte links instead of pointers +// (see arena.go). A member whose Go type is a pointer to a node or to a node list is stored +// as a link and read and written through accessors. + +function goFieldType(m: MemberInfo): string { + return m.goOnly ? m.rawType as string : m.type.formatGoReference(); +} + +/** The Go type a link member refers to, or undefined when the member is not stored as a link. */ +function linkTarget(m: MemberInfo): "Node" | "NodeList" | "ModifierList" | undefined { + return m.goLinkTarget(); +} + +/** The name of the Go field that stores a member. Links behind accessors are unexported. */ +function goFieldName(m: MemberInfo): string { + return linkTarget(m) && !m.private ? m.goParamName() : m.name; +} + +/** A Go expression that reads a member of `receiver`. */ +function goRead(m: MemberInfo, receiver = "node"): string { + if (!linkTarget(m)) return `${receiver}.${m.name}`; + return m.private ? `${receiver}.${m.name}.get()` : `${receiver}.${m.name}()`; +} + +function writeFieldDecl(w: CodeWriter, m: MemberInfo) { + const target = linkTarget(m); + const goType = target ? `link[${target}]` : goFieldType(m); + const notes: string[] = []; + if (target) notes.push(goFieldType(m)); + if (m.optional) notes.push("Optional"); + w.write(`${goFieldName(m)} ${goType}${notes.length > 0 ? ` // ${notes.join(". ")}` : ""}`); +} + +function writeLinkAccessors(w: CodeWriter, structName: string, m: MemberInfo) { + if (!linkTarget(m) || m.private) return; + const goType = goFieldType(m); + const field = goFieldName(m); + w.write(`func (node *${structName}) ${m.name}() ${goType} { return node.${field}.get() }`); + w.write(""); + w.write(`func (node *${structName}) Set${m.name}(${field} ${goType}) { node.${field}.set(${field}) }`); + w.write(""); +} + function generateHeader(w: CodeWriter) { w.write("// Code generated by tools/scripts/tsc/generate-go-ast.ts. DO NOT EDIT."); w.write(""); @@ -131,6 +164,7 @@ function generateHeader(w: CodeWriter) { w.write('"sync/atomic"'); w.write(""); w.write('"github.com/microsoft/TypeScript/tsc/internal/core"'); + w.write('"github.com/microsoft/TypeScript/tsc/internal/linkarena"'); w.pop(); w.write(")"); w.write(""); @@ -265,32 +299,22 @@ function generateStructDef(w: CodeWriter, node: NodeType) { if (node.members.length > 0) { for (const m of node.members) { if (m.inherited || m.isKindParam() || m.noGo) continue; - const fieldName = m.name; - const goType = m.goOnly ? m.rawType as string : m.type.formatGoReference(); - const comment = buildFieldComment(m); - if (comment) { - w.write(`${fieldName} ${goType} ${comment}`); - } - else { - w.write(`${fieldName} ${goType}`); - } + writeFieldDecl(w, m); } } w.pop(); w.write("}"); w.write(""); -} -function buildFieldComment(m: MemberInfo): string { - const parts: string[] = []; - if (m.optional) parts.push("Optional"); - if (parts.length > 0) return `// ${parts.join(". ")}`; - return ""; + for (const m of node.members) { + if (m.inherited || m.isKindParam() || m.noGo) continue; + writeLinkAccessors(w, structName, m); + } } function goSubtreeFactsTerm(m: MemberInfo): string { - const access = `node.${m.name}`; + const access = goRead(m); if (m.listKind === "ModifierList") { return `propagateModifierListSubtreeFacts(${access})`; } @@ -358,15 +382,18 @@ function generateBaseStructDefs(w: CodeWriter) { if (base.fields.length > 0) { for (const field of base.fields) { if (field.noGo) continue; - const goType = field.goOnly ? field.rawType as string : field.type.formatGoReference(); - const comment = field.optional ? " // Optional" : ""; - w.write(`${field.name} ${goType}${comment}`); + writeFieldDecl(w, field); } } w.pop(); w.write("}"); w.write(""); + + for (const field of base.fields) { + if (field.noGo) continue; + writeLinkAccessors(w, structName, field); + } } } @@ -404,18 +431,32 @@ function emitNewFactory( w.write(`func (f *NodeFactory) ${funcName}(${params}) *Node {`); w.push(); - if (node.arena) { - w.write(`data := f.${api.uncapitalize(structName)}Arena.New()`); - } - else { - w.write(`data := &${structName}{}`); - } + w.write(`data := newData[${structName}](f)`); for (const m of members) { if (m.isKindParam()) continue; if (isNodeFlagsMember(m)) continue; const value = m.bitmask ? `${m.goParamName()} & ${m.bitmask}` : m.goParamName(); + if (linkTarget(m)) { + w.write(`data.${goFieldName(m)}.set(${value})`); + continue; + } w.write(`data.${m.name} = ${value}`); + // The garbage collector does not look inside nodes, so the factory's arena has to keep + // the Go objects they refer to alive. + const goType = goFieldType(m); + if (goType === "string") { + w.write(`f.keepString(${m.goParamName()})`); + } + else if (goType === "[]*Node") { + w.write(`f.keepNodes(${m.goParamName()})`); + } + else if (goType.startsWith("[]")) { + w.write(`keepSlice(f, ${m.goParamName()})`); + } + else if (goType === "any") { + w.write(`f.keepValue(${m.goParamName()})`); + } } if (hasTextContent(node)) { @@ -486,7 +527,7 @@ function generateUpdateFactory(w: CodeWriter, node: NodeType) { if (type.kind === "list" && type.listKind === "raw") { return `!core.Same(${m.goParamName()}, node.${m.name})`; } - return `${m.goParamName()} != node.${m.name}`; + return `${m.goParamName()} != ${goRead(m)}`; }); w.write(`if ${comparisons.join(" || ")} {`); @@ -558,8 +599,7 @@ function generateForEachChild(w: CodeWriter, node: NodeType) { // Build visit chain: visit(v, node.Field) || visitNodeList(v, node.Field) || ... const parts = childMembers.map(m => { - const access = `node.${m.name}`; - const type = m.type; + const access = goRead(m); const listKind = m.listKind; if (listKind === "raw") { return `visitNodes(v, ${access})`; @@ -673,7 +713,7 @@ function generateVisitEachChild(w: CodeWriter, node: NodeType) { const args = updateMembers.map(m => { if (!m.isChild()) { - return `node.${m.name}`; + return goRead(m); } // Raw list: use the local variable @@ -681,7 +721,7 @@ function generateVisitEachChild(w: CodeWriter, node: NodeType) { return rawListLocals.get(m.name)!; } - const access = `node.${m.name}`; + const access = goRead(m); const type = m.type; const listKind = m.listKind; @@ -725,8 +765,8 @@ function generateClone(w: CodeWriter, node: NodeType) { if (m.inherited && type?.kind === "alias" && type.name === "ModifierLike") { return "node.Modifiers()"; } - // Use direct field access (Clone is a struct method, can access private fields) - return `node.${m.name}`; + // Clone is a struct method, so it can read private fields directly + return goRead(m); }).join(", "); if (node.kindAliases.length > 0) { @@ -870,7 +910,7 @@ function generateNameAccessor(w: CodeWriter, node: NodeType) { const structName = node.name; w.write(`func (node *${structName}) Name() *DeclarationName {`); w.push(); - w.write("return node.name"); + w.write(`return ${goRead(nameMember)}`); w.pop(); w.write("}"); w.write(""); diff --git a/tools/scripts/tsc/schema.ts b/tools/scripts/tsc/schema.ts index 6d2985d433435..84367523afeb8 100644 --- a/tools/scripts/tsc/schema.ts +++ b/tools/scripts/tsc/schema.ts @@ -29,7 +29,6 @@ export interface NodeDef { extends: string[]; members?: Member[]; generateSubtreeFacts?: boolean; - arena?: boolean; handWritten?: boolean; handWrittenVisitor?: boolean; typeParameters?: { name: string; constraint: string; default?: string; }[]; @@ -236,10 +235,6 @@ export class NodeType extends TypeBase { return this.fieldsCache; } - get arena(): boolean { - return this.def?.arena || false; - } - get handWritten(): boolean { return this.def?.handWritten || false; } @@ -716,6 +711,25 @@ export class MemberInfo { return false; } + /** + * The Go type this member refers to when its Go field is a 4-byte link rather than a + * pointer, which is the case for every pointer to a node or to a node list (see + * tsc/internal/ast/arena.go). Such a field is read and written through accessors. + */ + goLinkTarget(): "Node" | "NodeList" | "ModifierList" | undefined { + // Go-only fields keep their declared type. One of them, LocalsContainerBase.NextContainer, + // points to a node: it stays a pointer because a SourceFile, which has one, is an ordinary + // Go object and cannot hold links. It only ever points to a node of the same file. + if (this.goOnly) return undefined; + const goType = this.type.formatGoReference(); + if (goType === "*ModifierList") return "ModifierList"; + if (!goType.startsWith("*")) return undefined; + const base = this.type.baseKind(); + if (base === "node") return "Node"; + if (base === "list") return "NodeList"; + return undefined; + } + /** Go parameter name: uncapitalized, with Go keyword avoidance. */ goParamName(): string { const name = this.api.uncapitalize(this.name); diff --git a/tsc/internal/api/encoder/decoder_test.go b/tsc/internal/api/encoder/decoder_test.go index def2821cb6a25..46dbdab27e969 100644 --- a/tsc/internal/api/encoder/decoder_test.go +++ b/tsc/internal/api/encoder/decoder_test.go @@ -111,17 +111,17 @@ func TestDecodeSourceFile_VariableDeclaration(t *testing.T) { assert.NilError(t, err) varStmt := decoded.Statements.Nodes[0].AsVariableStatement() - assert.Assert(t, varStmt.DeclarationList != nil) - declList := varStmt.DeclarationList.AsVariableDeclarationList() - assert.Assert(t, declList.Declarations != nil) - assert.Equal(t, len(declList.Declarations.Nodes), 1) + assert.Assert(t, varStmt.DeclarationList() != nil) + declList := varStmt.DeclarationList().AsVariableDeclarationList() + assert.Assert(t, declList.Declarations() != nil) + assert.Equal(t, len(declList.Declarations().Nodes), 1) - decl := declList.Declarations.Nodes[0].AsVariableDeclaration() + decl := declList.Declarations().Nodes[0].AsVariableDeclaration() assert.Equal(t, decl.Name().Kind, ast.KindIdentifier) assert.Equal(t, decl.Name().AsIdentifier().Text, "x") - assert.Assert(t, decl.Initializer != nil) - assert.Equal(t, decl.Initializer.Kind, ast.KindNumericLiteral) - assert.Equal(t, decl.Initializer.AsNumericLiteral().Text, "1") + assert.Assert(t, decl.Initializer() != nil) + assert.Equal(t, decl.Initializer().Kind, ast.KindNumericLiteral) + assert.Equal(t, decl.Initializer().AsNumericLiteral().Text, "1") } func TestDecodeSourceFile_VariableDeclarationListFlags(t *testing.T) { @@ -147,7 +147,7 @@ func TestDecodeSourceFile_VariableDeclarationListFlags(t *testing.T) { decoded, err := encoder.DecodeSourceFile(buf) assert.NilError(t, err) - declList := decoded.Statements.Nodes[0].AsVariableStatement().DeclarationList.AsVariableDeclarationList() + declList := decoded.Statements.Nodes[0].AsVariableStatement().DeclarationList().AsVariableDeclarationList() got := declList.Flags & (ast.NodeFlagsLet | ast.NodeFlagsConst) assert.Equal(t, got, tt.expected, "flags for %q: got %d, want %d", tt.code, got, tt.expected) }) @@ -166,14 +166,14 @@ func TestDecodeSourceFile_FunctionDeclaration(t *testing.T) { funcDecl := decoded.Statements.Nodes[0].AsFunctionDeclaration() assert.Assert(t, funcDecl.Name() != nil) assert.Equal(t, funcDecl.Name().AsIdentifier().Text, "add") - assert.Assert(t, funcDecl.Parameters != nil) - assert.Equal(t, len(funcDecl.Parameters.Nodes), 2) - assert.Assert(t, funcDecl.Type != nil) - assert.Assert(t, funcDecl.Body != nil) + assert.Assert(t, funcDecl.Parameters() != nil) + assert.Equal(t, len(funcDecl.Parameters().Nodes), 2) + assert.Assert(t, funcDecl.Type() != nil) + assert.Assert(t, funcDecl.Body() != nil) - param0 := funcDecl.Parameters.Nodes[0].AsParameterDeclaration() + param0 := funcDecl.Parameters().Nodes[0].AsParameterDeclaration() assert.Equal(t, param0.Name().AsIdentifier().Text, "a") - assert.Assert(t, param0.Type != nil) + assert.Assert(t, param0.Type() != nil) } func TestDecodeSourceFile_ImportDeclaration(t *testing.T) { @@ -186,16 +186,16 @@ func TestDecodeSourceFile_ImportDeclaration(t *testing.T) { assert.NilError(t, err) imp := decoded.Statements.Nodes[0].AsImportDeclaration() - assert.Assert(t, imp.ImportClause != nil) - assert.Assert(t, imp.ModuleSpecifier != nil) - assert.Equal(t, imp.ModuleSpecifier.AsStringLiteral().Text, "bar") - - clause := imp.ImportClause.AsImportClause() - assert.Assert(t, clause.NamedBindings != nil) - namedImports := clause.NamedBindings.AsNamedImports() - assert.Assert(t, namedImports.Elements != nil) - assert.Equal(t, len(namedImports.Elements.Nodes), 1) - spec := namedImports.Elements.Nodes[0].AsImportSpecifier() + assert.Assert(t, imp.ImportClause() != nil) + assert.Assert(t, imp.ModuleSpecifier() != nil) + assert.Equal(t, imp.ModuleSpecifier().AsStringLiteral().Text, "bar") + + clause := imp.ImportClause().AsImportClause() + assert.Assert(t, clause.NamedBindings() != nil) + namedImports := clause.NamedBindings().AsNamedImports() + assert.Assert(t, namedImports.Elements() != nil) + assert.Equal(t, len(namedImports.Elements().Nodes), 1) + spec := namedImports.Elements().Nodes[0].AsImportSpecifier() assert.Equal(t, spec.Name().AsIdentifier().Text, "bar") } @@ -208,7 +208,7 @@ func TestDecodeSourceFile_SourcePhaseImport(t *testing.T) { decoded, err := encoder.DecodeSourceFile(buf) assert.NilError(t, err) - clause := decoded.Statements.Nodes[0].AsImportDeclaration().ImportClause.AsImportClause() + clause := decoded.Statements.Nodes[0].AsImportDeclaration().ImportClause().AsImportClause() assert.Equal(t, clause.PhaseModifier, ast.KindSourceKeyword) assert.Equal(t, clause.Name().Text(), "a") } @@ -223,11 +223,11 @@ func TestDecodeSourceFile_IfStatement(t *testing.T) { assert.NilError(t, err) ifStmt := decoded.Statements.Nodes[0].AsIfStatement() - assert.Assert(t, ifStmt.Expression != nil) - assert.Assert(t, ifStmt.ThenStatement != nil) - assert.Assert(t, ifStmt.ElseStatement != nil) - assert.Equal(t, ifStmt.ThenStatement.Kind, ast.KindBlock) - assert.Equal(t, ifStmt.ElseStatement.Kind, ast.KindBlock) + assert.Assert(t, ifStmt.Expression() != nil) + assert.Assert(t, ifStmt.ThenStatement() != nil) + assert.Assert(t, ifStmt.ElseStatement() != nil) + assert.Equal(t, ifStmt.ThenStatement().Kind, ast.KindBlock) + assert.Equal(t, ifStmt.ElseStatement().Kind, ast.KindBlock) } func TestDecodeSourceFile_TemplateExpression(t *testing.T) { @@ -239,18 +239,18 @@ func TestDecodeSourceFile_TemplateExpression(t *testing.T) { decoded, err := encoder.DecodeSourceFile(buf) assert.NilError(t, err) - varDecl := decoded.Statements.Nodes[0].AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes[0].AsVariableDeclaration() - tmplExpr := varDecl.Initializer.AsTemplateExpression() - assert.Assert(t, tmplExpr.Head != nil) - assert.Equal(t, tmplExpr.Head.AsTemplateHead().Text, "hello ") - assert.Assert(t, tmplExpr.TemplateSpans != nil) - assert.Equal(t, len(tmplExpr.TemplateSpans.Nodes), 1) + varDecl := decoded.Statements.Nodes[0].AsVariableStatement().DeclarationList().AsVariableDeclarationList().Declarations().Nodes[0].AsVariableDeclaration() + tmplExpr := varDecl.Initializer().AsTemplateExpression() + assert.Assert(t, tmplExpr.Head() != nil) + assert.Equal(t, tmplExpr.Head().AsTemplateHead().Text, "hello ") + assert.Assert(t, tmplExpr.TemplateSpans() != nil) + assert.Equal(t, len(tmplExpr.TemplateSpans().Nodes), 1) - span := tmplExpr.TemplateSpans.Nodes[0].AsTemplateSpan() - assert.Assert(t, span.Expression != nil) - assert.Equal(t, span.Expression.Kind, ast.KindIdentifier) - assert.Assert(t, span.Literal != nil) - assert.Equal(t, span.Literal.AsTemplateTail().Text, " world") + span := tmplExpr.TemplateSpans().Nodes[0].AsTemplateSpan() + assert.Assert(t, span.Expression() != nil) + assert.Equal(t, span.Expression().Kind, ast.KindIdentifier) + assert.Assert(t, span.Literal() != nil) + assert.Equal(t, span.Literal().AsTemplateTail().Text, " world") } func TestDecodeSourceFile_ExportModifier(t *testing.T) { @@ -294,9 +294,9 @@ func TestDecodeSourceFile_ClassDeclaration(t *testing.T) { classDecl := decoded.Statements.Nodes[0].AsClassDeclaration() assert.Assert(t, classDecl.Name() != nil) assert.Equal(t, classDecl.Name().AsIdentifier().Text, "Foo") - assert.Assert(t, classDecl.Members != nil) - assert.Equal(t, len(classDecl.Members.Nodes), 1) - assert.Equal(t, classDecl.Members.Nodes[0].Kind, ast.KindMethodDeclaration) + assert.Assert(t, classDecl.Members() != nil) + assert.Equal(t, len(classDecl.Members().Nodes), 1) + assert.Equal(t, classDecl.Members().Nodes[0].Kind, ast.KindMethodDeclaration) } func TestDecodeNodes_SubtreeRoundTrip(t *testing.T) { @@ -324,9 +324,9 @@ func TestDecodeNodes_SubtreeRoundTrip(t *testing.T) { funcDecl := decoded.AsFunctionDeclaration() assert.Assert(t, funcDecl.Name() != nil) assert.Equal(t, funcDecl.Name().AsIdentifier().Text, "greet") - assert.Assert(t, funcDecl.Parameters != nil) - assert.Equal(t, len(funcDecl.Parameters.Nodes), 1) - assert.Assert(t, funcDecl.Body != nil) + assert.Assert(t, funcDecl.Parameters() != nil) + assert.Equal(t, len(funcDecl.Parameters().Nodes), 1) + assert.Assert(t, funcDecl.Body() != nil) } func TestDecodeSourceFile_BinaryExpression(t *testing.T) { @@ -338,13 +338,13 @@ func TestDecodeSourceFile_BinaryExpression(t *testing.T) { decoded, err := encoder.DecodeSourceFile(buf) assert.NilError(t, err) - decl := decoded.Statements.Nodes[0].AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes[0].AsVariableDeclaration() - binExpr := decl.Initializer.AsBinaryExpression() - assert.Assert(t, binExpr.Left != nil) - assert.Assert(t, binExpr.Right != nil) - assert.Assert(t, binExpr.OperatorToken != nil) - assert.Equal(t, binExpr.Left.Kind, ast.KindNumericLiteral) - assert.Equal(t, binExpr.Right.Kind, ast.KindNumericLiteral) + decl := decoded.Statements.Nodes[0].AsVariableStatement().DeclarationList().AsVariableDeclarationList().Declarations().Nodes[0].AsVariableDeclaration() + binExpr := decl.Initializer().AsBinaryExpression() + assert.Assert(t, binExpr.Left() != nil) + assert.Assert(t, binExpr.Right() != nil) + assert.Assert(t, binExpr.OperatorToken() != nil) + assert.Equal(t, binExpr.Left().Kind, ast.KindNumericLiteral) + assert.Equal(t, binExpr.Right().Kind, ast.KindNumericLiteral) } func TestDecodeSourceFile_KeywordExpressions(t *testing.T) { @@ -358,8 +358,8 @@ func TestDecodeSourceFile_KeywordExpressions(t *testing.T) { assert.NilError(t, err) // Navigate: const x = this -> VariableStatement -> declaration -> initializer - decl := decoded.Statements.Nodes[0].AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes[0].AsVariableDeclaration() - thisExpr := decl.Initializer + decl := decoded.Statements.Nodes[0].AsVariableStatement().DeclarationList().AsVariableDeclarationList().Declarations().Nodes[0].AsVariableDeclaration() + thisExpr := decl.Initializer() assert.Equal(t, thisExpr.Kind, ast.KindThisKeyword) // This would panic if decoded as Token instead of KeywordExpression assert.Assert(t, thisExpr.AsKeywordExpression() != nil) @@ -376,11 +376,11 @@ func TestDecodeSourceFile_EmptyModuleBlock(t *testing.T) { // Navigate: namespace N { } -> ModuleDeclaration -> ModuleBlock mod := decoded.Statements.Nodes[0].AsModuleDeclaration() - assert.Assert(t, mod.Body != nil) - block := mod.Body.AsModuleBlock() + assert.Assert(t, mod.Body() != nil) + block := mod.Body().AsModuleBlock() // Statements must be non-nil even when empty, otherwise the printer panics - assert.Assert(t, block.Statements != nil) - assert.Equal(t, len(block.Statements.Nodes), 0) + assert.Assert(t, block.Statements() != nil) + assert.Equal(t, len(block.Statements().Nodes), 0) } func TestDecodeSourceFile_EmptyBlockAndParams(t *testing.T) { @@ -395,12 +395,12 @@ func TestDecodeSourceFile_EmptyBlockAndParams(t *testing.T) { assert.NilError(t, err) funcDecl := decoded.Statements.Nodes[0].AsFunctionDeclaration() - assert.Assert(t, funcDecl.Parameters != nil, "FunctionDeclaration.Parameters must be non-nil for foo()") - assert.Equal(t, len(funcDecl.Parameters.Nodes), 0) - assert.Assert(t, funcDecl.Body != nil) - block := funcDecl.Body.AsBlock() - assert.Assert(t, block.Statements != nil, "Block.Statements must be non-nil for empty blocks") - assert.Equal(t, len(block.Statements.Nodes), 0) + assert.Assert(t, funcDecl.Parameters() != nil, "FunctionDeclaration.Parameters must be non-nil for foo()") + assert.Equal(t, len(funcDecl.Parameters().Nodes), 0) + assert.Assert(t, funcDecl.Body() != nil) + block := funcDecl.Body().AsBlock() + assert.Assert(t, block.Statements() != nil, "Block.Statements must be non-nil for empty blocks") + assert.Equal(t, len(block.Statements().Nodes), 0) } func TestDecodeSourceFile_ArrowFunctionEmptyParams(t *testing.T) { @@ -414,14 +414,14 @@ func TestDecodeSourceFile_ArrowFunctionEmptyParams(t *testing.T) { decoded, err := encoder.DecodeSourceFile(buf) assert.NilError(t, err) - decl := decoded.Statements.Nodes[0].AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes[0].AsVariableDeclaration() - arrow := decl.Initializer.AsArrowFunction() - assert.Assert(t, arrow.Parameters != nil, "ArrowFunction.Parameters must be non-nil for () => {}") - assert.Equal(t, len(arrow.Parameters.Nodes), 0) - assert.Assert(t, arrow.Body != nil) - block := arrow.Body.AsBlock() - assert.Assert(t, block.Statements != nil, "Block.Statements must be non-nil for empty body") - assert.Equal(t, len(block.Statements.Nodes), 0) + decl := decoded.Statements.Nodes[0].AsVariableStatement().DeclarationList().AsVariableDeclarationList().Declarations().Nodes[0].AsVariableDeclaration() + arrow := decl.Initializer().AsArrowFunction() + assert.Assert(t, arrow.Parameters() != nil, "ArrowFunction.Parameters must be non-nil for () => {}") + assert.Equal(t, len(arrow.Parameters().Nodes), 0) + assert.Assert(t, arrow.Body() != nil) + block := arrow.Body().AsBlock() + assert.Assert(t, block.Statements() != nil, "Block.Statements must be non-nil for empty body") + assert.Equal(t, len(block.Statements().Nodes), 0) } func TestDecodeSourceFile_FunctionExpressionEmptyParams(t *testing.T) { @@ -434,10 +434,10 @@ func TestDecodeSourceFile_FunctionExpressionEmptyParams(t *testing.T) { decoded, err := encoder.DecodeSourceFile(buf) assert.NilError(t, err) - decl := decoded.Statements.Nodes[0].AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes[0].AsVariableDeclaration() - funcExpr := decl.Initializer.AsFunctionExpression() - assert.Assert(t, funcExpr.Parameters != nil, "FunctionExpression.Parameters must be non-nil for function() {}") - assert.Equal(t, len(funcExpr.Parameters.Nodes), 0) + decl := decoded.Statements.Nodes[0].AsVariableStatement().DeclarationList().AsVariableDeclarationList().Declarations().Nodes[0].AsVariableDeclaration() + funcExpr := decl.Initializer().AsFunctionExpression() + assert.Assert(t, funcExpr.Parameters() != nil, "FunctionExpression.Parameters must be non-nil for function() {}") + assert.Equal(t, len(funcExpr.Parameters().Nodes), 0) } func TestDecodeSourceFile_PostfixUnaryOperator(t *testing.T) { @@ -450,9 +450,9 @@ func TestDecodeSourceFile_PostfixUnaryOperator(t *testing.T) { assert.NilError(t, err) exprStmt := decoded.Statements.Nodes[1].AsExpressionStatement() - postfix := exprStmt.Expression.AsPostfixUnaryExpression() + postfix := exprStmt.Expression().AsPostfixUnaryExpression() assert.Equal(t, postfix.Operator, ast.KindPlusPlusToken) - assert.Equal(t, postfix.Operand.Kind, ast.KindIdentifier) + assert.Equal(t, postfix.Operand().Kind, ast.KindIdentifier) } func TestDecodeSourceFile_PrefixUnaryOperator(t *testing.T) { @@ -465,9 +465,9 @@ func TestDecodeSourceFile_PrefixUnaryOperator(t *testing.T) { assert.NilError(t, err) exprStmt := decoded.Statements.Nodes[1].AsExpressionStatement() - prefix := exprStmt.Expression.AsPrefixUnaryExpression() + prefix := exprStmt.Expression().AsPrefixUnaryExpression() assert.Equal(t, prefix.Operator, ast.KindExclamationToken) - assert.Equal(t, prefix.Operand.Kind, ast.KindIdentifier) + assert.Equal(t, prefix.Operand().Kind, ast.KindIdentifier) } func TestDecodeSourceFile_PostfixDecrement(t *testing.T) { @@ -480,7 +480,7 @@ func TestDecodeSourceFile_PostfixDecrement(t *testing.T) { assert.NilError(t, err) exprStmt := decoded.Statements.Nodes[1].AsExpressionStatement() - postfix := exprStmt.Expression.AsPostfixUnaryExpression() + postfix := exprStmt.Expression().AsPostfixUnaryExpression() assert.Equal(t, postfix.Operator, ast.KindMinusMinusToken) } diff --git a/tsc/internal/api/encoder/encoder_generated.go b/tsc/internal/api/encoder/encoder_generated.go index 3f695dabfb03a..af91b4b7b6a11 100644 --- a/tsc/internal/api/encoder/encoder_generated.go +++ b/tsc/internal/api/encoder/encoder_generated.go @@ -37,130 +37,130 @@ func getChildrenPropertyMask(node *ast.Node) uint8 { switch node.Kind { case ast.KindQualifiedName: n := node.AsQualifiedName() - return (boolToByte(n.Left != nil) << 0) | (boolToByte(n.Right != nil) << 1) + return (boolToByte(n.Left() != nil) << 0) | (boolToByte(n.Right() != nil) << 1) case ast.KindComputedPropertyName: n := node.AsComputedPropertyName() - return (boolToByte(n.Expression != nil) << 0) + return (boolToByte(n.Expression() != nil) << 0) case ast.KindDecorator: n := node.AsDecorator() - return (boolToByte(n.Expression != nil) << 0) + return (boolToByte(n.Expression() != nil) << 0) case ast.KindIfStatement: n := node.AsIfStatement() - return (boolToByte(n.Expression != nil) << 0) | (boolToByte(n.ThenStatement != nil) << 1) | (boolToByte(n.ElseStatement != nil) << 2) + return (boolToByte(n.Expression() != nil) << 0) | (boolToByte(n.ThenStatement() != nil) << 1) | (boolToByte(n.ElseStatement() != nil) << 2) case ast.KindDoStatement: n := node.AsDoStatement() - return (boolToByte(n.Statement != nil) << 0) | (boolToByte(n.Expression != nil) << 1) + return (boolToByte(n.Statement() != nil) << 0) | (boolToByte(n.Expression() != nil) << 1) case ast.KindWhileStatement: n := node.AsWhileStatement() - return (boolToByte(n.Expression != nil) << 0) | (boolToByte(n.Statement != nil) << 1) + return (boolToByte(n.Expression() != nil) << 0) | (boolToByte(n.Statement() != nil) << 1) case ast.KindForStatement: n := node.AsForStatement() - return (boolToByte(n.Initializer != nil) << 0) | (boolToByte(n.Condition != nil) << 1) | (boolToByte(n.Incrementor != nil) << 2) | (boolToByte(n.Statement != nil) << 3) + return (boolToByte(n.Initializer() != nil) << 0) | (boolToByte(n.Condition() != nil) << 1) | (boolToByte(n.Incrementor() != nil) << 2) | (boolToByte(n.Statement() != nil) << 3) case ast.KindForInStatement, ast.KindForOfStatement: n := node.AsForInOrOfStatement() - return (boolToByte(n.AwaitModifier != nil) << 0) | (boolToByte(n.Initializer != nil) << 1) | (boolToByte(n.Expression != nil) << 2) | (boolToByte(n.Statement != nil) << 3) + return (boolToByte(n.AwaitModifier() != nil) << 0) | (boolToByte(n.Initializer() != nil) << 1) | (boolToByte(n.Expression() != nil) << 2) | (boolToByte(n.Statement() != nil) << 3) case ast.KindBreakStatement: n := node.AsBreakStatement() - return (boolToByte(n.Label != nil) << 0) + return (boolToByte(n.Label() != nil) << 0) case ast.KindContinueStatement: n := node.AsContinueStatement() - return (boolToByte(n.Label != nil) << 0) + return (boolToByte(n.Label() != nil) << 0) case ast.KindReturnStatement: n := node.AsReturnStatement() - return (boolToByte(n.Expression != nil) << 0) + return (boolToByte(n.Expression() != nil) << 0) case ast.KindWithStatement: n := node.AsWithStatement() - return (boolToByte(n.Expression != nil) << 0) | (boolToByte(n.Statement != nil) << 1) + return (boolToByte(n.Expression() != nil) << 0) | (boolToByte(n.Statement() != nil) << 1) case ast.KindSwitchStatement: n := node.AsSwitchStatement() - return (boolToByte(n.Expression != nil) << 0) | (boolToByte(n.CaseBlock != nil) << 1) + return (boolToByte(n.Expression() != nil) << 0) | (boolToByte(n.CaseBlock() != nil) << 1) case ast.KindCaseBlock: n := node.AsCaseBlock() - return (boolToByte(n.Clauses != nil) << 0) + return (boolToByte(n.Clauses() != nil) << 0) case ast.KindCaseClause, ast.KindDefaultClause: n := node.AsCaseOrDefaultClause() - return (boolToByte(n.Expression != nil) << 0) | (boolToByte(n.Statements != nil) << 1) + return (boolToByte(n.Expression() != nil) << 0) | (boolToByte(n.Statements() != nil) << 1) case ast.KindThrowStatement: n := node.AsThrowStatement() - return (boolToByte(n.Expression != nil) << 0) + return (boolToByte(n.Expression() != nil) << 0) case ast.KindTryStatement: n := node.AsTryStatement() - return (boolToByte(n.TryBlock != nil) << 0) | (boolToByte(n.CatchClause != nil) << 1) | (boolToByte(n.FinallyBlock != nil) << 2) + return (boolToByte(n.TryBlock() != nil) << 0) | (boolToByte(n.CatchClause() != nil) << 1) | (boolToByte(n.FinallyBlock() != nil) << 2) case ast.KindCatchClause: n := node.AsCatchClause() - return (boolToByte(n.VariableDeclaration != nil) << 0) | (boolToByte(n.Block != nil) << 1) + return (boolToByte(n.VariableDeclaration() != nil) << 0) | (boolToByte(n.Block() != nil) << 1) case ast.KindLabeledStatement: n := node.AsLabeledStatement() - return (boolToByte(n.Label != nil) << 0) | (boolToByte(n.Statement != nil) << 1) + return (boolToByte(n.Label() != nil) << 0) | (boolToByte(n.Statement() != nil) << 1) case ast.KindExpressionStatement: n := node.AsExpressionStatement() - return (boolToByte(n.Expression != nil) << 0) + return (boolToByte(n.Expression() != nil) << 0) case ast.KindBlock: n := node.AsBlock() - return (boolToByte(n.Statements != nil) << 0) + return (boolToByte(n.Statements() != nil) << 0) case ast.KindVariableStatement: n := node.AsVariableStatement() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.DeclarationList != nil) << 1) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.DeclarationList() != nil) << 1) case ast.KindVariableDeclaration: n := node.AsVariableDeclaration() - return (boolToByte(n.Name() != nil) << 0) | (boolToByte(n.ExclamationToken != nil) << 1) | (boolToByte(n.Type != nil) << 2) | (boolToByte(n.Initializer != nil) << 3) + return (boolToByte(n.Name() != nil) << 0) | (boolToByte(n.ExclamationToken() != nil) << 1) | (boolToByte(n.Type() != nil) << 2) | (boolToByte(n.Initializer() != nil) << 3) case ast.KindVariableDeclarationList: n := node.AsVariableDeclarationList() - return (boolToByte(n.Declarations != nil) << 0) + return (boolToByte(n.Declarations() != nil) << 0) case ast.KindObjectBindingPattern, ast.KindArrayBindingPattern: n := node.AsBindingPattern() - return (boolToByte(n.Elements != nil) << 0) + return (boolToByte(n.Elements() != nil) << 0) case ast.KindParameter: n := node.AsParameterDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.DotDotDotToken != nil) << 1) | (boolToByte(n.Name() != nil) << 2) | (boolToByte(n.QuestionToken != nil) << 3) | (boolToByte(n.Type != nil) << 4) | (boolToByte(n.Initializer != nil) << 5) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.DotDotDotToken() != nil) << 1) | (boolToByte(n.Name() != nil) << 2) | (boolToByte(n.QuestionToken() != nil) << 3) | (boolToByte(n.Type() != nil) << 4) | (boolToByte(n.Initializer() != nil) << 5) case ast.KindBindingElement: n := node.AsBindingElement() - return (boolToByte(n.DotDotDotToken != nil) << 0) | (boolToByte(n.PropertyName != nil) << 1) | (boolToByte(n.Name() != nil) << 2) | (boolToByte(n.Initializer != nil) << 3) + return (boolToByte(n.DotDotDotToken() != nil) << 0) | (boolToByte(n.PropertyName() != nil) << 1) | (boolToByte(n.Name() != nil) << 2) | (boolToByte(n.Initializer() != nil) << 3) case ast.KindMissingDeclaration: n := node.AsMissingDeclaration() return (boolToByte(hasModifiers(n.Modifiers())) << 0) case ast.KindFunctionDeclaration: n := node.AsFunctionDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.AsteriskToken != nil) << 1) | (boolToByte(n.Name() != nil) << 2) | (boolToByte(n.TypeParameters != nil) << 3) | (boolToByte(n.Parameters != nil) << 4) | (boolToByte(n.Type != nil) << 5) | (boolToByte(n.Body != nil) << 6) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.AsteriskToken() != nil) << 1) | (boolToByte(n.Name() != nil) << 2) | (boolToByte(n.TypeParameters() != nil) << 3) | (boolToByte(n.Parameters() != nil) << 4) | (boolToByte(n.Type() != nil) << 5) | (boolToByte(n.Body() != nil) << 6) case ast.KindClassDeclaration: n := node.AsClassDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.TypeParameters != nil) << 2) | (boolToByte(n.HeritageClauses != nil) << 3) | (boolToByte(n.Members != nil) << 4) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.TypeParameters() != nil) << 2) | (boolToByte(n.HeritageClauses() != nil) << 3) | (boolToByte(n.Members() != nil) << 4) case ast.KindClassExpression: n := node.AsClassExpression() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.TypeParameters != nil) << 2) | (boolToByte(n.HeritageClauses != nil) << 3) | (boolToByte(n.Members != nil) << 4) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.TypeParameters() != nil) << 2) | (boolToByte(n.HeritageClauses() != nil) << 3) | (boolToByte(n.Members() != nil) << 4) case ast.KindHeritageClause: n := node.AsHeritageClause() - return (boolToByte(n.Types != nil) << 0) + return (boolToByte(n.Types() != nil) << 0) case ast.KindInterfaceDeclaration: n := node.AsInterfaceDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.TypeParameters != nil) << 2) | (boolToByte(n.HeritageClauses != nil) << 3) | (boolToByte(n.Members != nil) << 4) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.TypeParameters() != nil) << 2) | (boolToByte(n.HeritageClauses() != nil) << 3) | (boolToByte(n.Members() != nil) << 4) case ast.KindTypeAliasDeclaration, ast.KindJSTypeAliasDeclaration: n := node.AsTypeAliasDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.TypeParameters != nil) << 2) | (boolToByte(n.Type != nil) << 3) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.TypeParameters() != nil) << 2) | (boolToByte(n.Type() != nil) << 3) case ast.KindEnumMember: n := node.AsEnumMember() - return (boolToByte(n.Name() != nil) << 0) | (boolToByte(n.Initializer != nil) << 1) + return (boolToByte(n.Name() != nil) << 0) | (boolToByte(n.Initializer() != nil) << 1) case ast.KindEnumDeclaration: n := node.AsEnumDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.Members != nil) << 2) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.Members() != nil) << 2) case ast.KindModuleBlock: n := node.AsModuleBlock() - return (boolToByte(n.Statements != nil) << 0) + return (boolToByte(n.Statements() != nil) << 0) case ast.KindImportDeclaration, ast.KindJSImportDeclaration: n := node.AsImportDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.ImportClause != nil) << 1) | (boolToByte(n.ModuleSpecifier != nil) << 2) | (boolToByte(n.Attributes != nil) << 3) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.ImportClause() != nil) << 1) | (boolToByte(n.ModuleSpecifier() != nil) << 2) | (boolToByte(n.Attributes() != nil) << 3) case ast.KindExternalModuleReference: n := node.AsExternalModuleReference() - return (boolToByte(n.Expression != nil) << 0) + return (boolToByte(n.Expression() != nil) << 0) case ast.KindNamespaceImport: n := node.AsNamespaceImport() return (boolToByte(n.Name() != nil) << 0) case ast.KindNamedImports: n := node.AsNamedImports() - return (boolToByte(n.Elements != nil) << 0) + return (boolToByte(n.Elements() != nil) << 0) case ast.KindExportAssignment: n := node.AsExportAssignment() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Type != nil) << 1) | (boolToByte(n.Expression != nil) << 2) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Type() != nil) << 1) | (boolToByte(n.Expression() != nil) << 2) case ast.KindNamespaceExportDeclaration: n := node.AsNamespaceExportDeclaration() return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) @@ -169,349 +169,349 @@ func getChildrenPropertyMask(node *ast.Node) uint8 { return (boolToByte(n.Name() != nil) << 0) case ast.KindNamedExports: n := node.AsNamedExports() - return (boolToByte(n.Elements != nil) << 0) + return (boolToByte(n.Elements() != nil) << 0) case ast.KindExportSpecifier: n := node.AsExportSpecifier() - return (boolToByte(n.PropertyName != nil) << 0) | (boolToByte(n.Name() != nil) << 1) + return (boolToByte(n.PropertyName() != nil) << 0) | (boolToByte(n.Name() != nil) << 1) case ast.KindCallSignature: n := node.AsCallSignatureDeclaration() - return (boolToByte(n.TypeParameters != nil) << 0) | (boolToByte(n.Parameters != nil) << 1) | (boolToByte(n.Type != nil) << 2) + return (boolToByte(n.TypeParameters() != nil) << 0) | (boolToByte(n.Parameters() != nil) << 1) | (boolToByte(n.Type() != nil) << 2) case ast.KindConstructSignature: n := node.AsConstructSignatureDeclaration() - return (boolToByte(n.TypeParameters != nil) << 0) | (boolToByte(n.Parameters != nil) << 1) | (boolToByte(n.Type != nil) << 2) + return (boolToByte(n.TypeParameters() != nil) << 0) | (boolToByte(n.Parameters() != nil) << 1) | (boolToByte(n.Type() != nil) << 2) case ast.KindConstructor: n := node.AsConstructorDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.TypeParameters != nil) << 1) | (boolToByte(n.Parameters != nil) << 2) | (boolToByte(n.Type != nil) << 3) | (boolToByte(n.Body != nil) << 4) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.TypeParameters() != nil) << 1) | (boolToByte(n.Parameters() != nil) << 2) | (boolToByte(n.Type() != nil) << 3) | (boolToByte(n.Body() != nil) << 4) case ast.KindGetAccessor: n := node.AsGetAccessorDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.TypeParameters != nil) << 2) | (boolToByte(n.Parameters != nil) << 3) | (boolToByte(n.Type != nil) << 4) | (boolToByte(n.Body != nil) << 5) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.TypeParameters() != nil) << 2) | (boolToByte(n.Parameters() != nil) << 3) | (boolToByte(n.Type() != nil) << 4) | (boolToByte(n.Body() != nil) << 5) case ast.KindSetAccessor: n := node.AsSetAccessorDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.TypeParameters != nil) << 2) | (boolToByte(n.Parameters != nil) << 3) | (boolToByte(n.Type != nil) << 4) | (boolToByte(n.Body != nil) << 5) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.TypeParameters() != nil) << 2) | (boolToByte(n.Parameters() != nil) << 3) | (boolToByte(n.Type() != nil) << 4) | (boolToByte(n.Body() != nil) << 5) case ast.KindIndexSignature: n := node.AsIndexSignatureDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Parameters != nil) << 1) | (boolToByte(n.Type != nil) << 2) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Parameters() != nil) << 1) | (boolToByte(n.Type() != nil) << 2) case ast.KindMethodSignature: n := node.AsMethodSignatureDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.PostfixToken != nil) << 2) | (boolToByte(n.TypeParameters != nil) << 3) | (boolToByte(n.Parameters != nil) << 4) | (boolToByte(n.Type != nil) << 5) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.PostfixToken() != nil) << 2) | (boolToByte(n.TypeParameters() != nil) << 3) | (boolToByte(n.Parameters() != nil) << 4) | (boolToByte(n.Type() != nil) << 5) case ast.KindMethodDeclaration: n := node.AsMethodDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.AsteriskToken != nil) << 1) | (boolToByte(n.Name() != nil) << 2) | (boolToByte(n.PostfixToken != nil) << 3) | (boolToByte(n.TypeParameters != nil) << 4) | (boolToByte(n.Parameters != nil) << 5) | (boolToByte(n.Type != nil) << 6) | (boolToByte(n.Body != nil) << 7) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.AsteriskToken() != nil) << 1) | (boolToByte(n.Name() != nil) << 2) | (boolToByte(n.PostfixToken() != nil) << 3) | (boolToByte(n.TypeParameters() != nil) << 4) | (boolToByte(n.Parameters() != nil) << 5) | (boolToByte(n.Type() != nil) << 6) | (boolToByte(n.Body() != nil) << 7) case ast.KindPropertySignature: n := node.AsPropertySignatureDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.PostfixToken != nil) << 2) | (boolToByte(n.Type != nil) << 3) | (boolToByte(n.Initializer != nil) << 4) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.PostfixToken() != nil) << 2) | (boolToByte(n.Type() != nil) << 3) | (boolToByte(n.Initializer() != nil) << 4) case ast.KindPropertyDeclaration: n := node.AsPropertyDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.PostfixToken != nil) << 2) | (boolToByte(n.Type != nil) << 3) | (boolToByte(n.Initializer != nil) << 4) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.PostfixToken() != nil) << 2) | (boolToByte(n.Type() != nil) << 3) | (boolToByte(n.Initializer() != nil) << 4) case ast.KindClassStaticBlockDeclaration: n := node.AsClassStaticBlockDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Body != nil) << 1) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Body() != nil) << 1) case ast.KindBinaryExpression: n := node.AsBinaryExpression() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Left != nil) << 1) | (boolToByte(n.Type != nil) << 2) | (boolToByte(n.OperatorToken != nil) << 3) | (boolToByte(n.Right != nil) << 4) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Left() != nil) << 1) | (boolToByte(n.Type() != nil) << 2) | (boolToByte(n.OperatorToken() != nil) << 3) | (boolToByte(n.Right() != nil) << 4) case ast.KindPrefixUnaryExpression: n := node.AsPrefixUnaryExpression() - return (boolToByte(n.Operand != nil) << 0) + return (boolToByte(n.Operand() != nil) << 0) case ast.KindPostfixUnaryExpression: n := node.AsPostfixUnaryExpression() - return (boolToByte(n.Operand != nil) << 0) + return (boolToByte(n.Operand() != nil) << 0) case ast.KindYieldExpression: n := node.AsYieldExpression() - return (boolToByte(n.AsteriskToken != nil) << 0) | (boolToByte(n.Expression != nil) << 1) + return (boolToByte(n.AsteriskToken() != nil) << 0) | (boolToByte(n.Expression() != nil) << 1) case ast.KindArrowFunction: n := node.AsArrowFunction() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.TypeParameters != nil) << 1) | (boolToByte(n.Parameters != nil) << 2) | (boolToByte(n.Type != nil) << 3) | (boolToByte(n.EqualsGreaterThanToken != nil) << 4) | (boolToByte(n.Body != nil) << 5) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.TypeParameters() != nil) << 1) | (boolToByte(n.Parameters() != nil) << 2) | (boolToByte(n.Type() != nil) << 3) | (boolToByte(n.EqualsGreaterThanToken() != nil) << 4) | (boolToByte(n.Body() != nil) << 5) case ast.KindFunctionExpression: n := node.AsFunctionExpression() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.AsteriskToken != nil) << 1) | (boolToByte(n.Name() != nil) << 2) | (boolToByte(n.TypeParameters != nil) << 3) | (boolToByte(n.Parameters != nil) << 4) | (boolToByte(n.Type != nil) << 5) | (boolToByte(n.Body != nil) << 6) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.AsteriskToken() != nil) << 1) | (boolToByte(n.Name() != nil) << 2) | (boolToByte(n.TypeParameters() != nil) << 3) | (boolToByte(n.Parameters() != nil) << 4) | (boolToByte(n.Type() != nil) << 5) | (boolToByte(n.Body() != nil) << 6) case ast.KindAsExpression: n := node.AsAsExpression() - return (boolToByte(n.Expression != nil) << 0) | (boolToByte(n.Type != nil) << 1) + return (boolToByte(n.Expression() != nil) << 0) | (boolToByte(n.Type() != nil) << 1) case ast.KindSatisfiesExpression: n := node.AsSatisfiesExpression() - return (boolToByte(n.Expression != nil) << 0) | (boolToByte(n.Type != nil) << 1) + return (boolToByte(n.Expression() != nil) << 0) | (boolToByte(n.Type() != nil) << 1) case ast.KindConditionalExpression: n := node.AsConditionalExpression() - return (boolToByte(n.Condition != nil) << 0) | (boolToByte(n.QuestionToken != nil) << 1) | (boolToByte(n.WhenTrue != nil) << 2) | (boolToByte(n.ColonToken != nil) << 3) | (boolToByte(n.WhenFalse != nil) << 4) + return (boolToByte(n.Condition() != nil) << 0) | (boolToByte(n.QuestionToken() != nil) << 1) | (boolToByte(n.WhenTrue() != nil) << 2) | (boolToByte(n.ColonToken() != nil) << 3) | (boolToByte(n.WhenFalse() != nil) << 4) case ast.KindPropertyAccessExpression: n := node.AsPropertyAccessExpression() - return (boolToByte(n.Expression != nil) << 0) | (boolToByte(n.QuestionDotToken != nil) << 1) | (boolToByte(n.Name() != nil) << 2) + return (boolToByte(n.Expression() != nil) << 0) | (boolToByte(n.QuestionDotToken() != nil) << 1) | (boolToByte(n.Name() != nil) << 2) case ast.KindElementAccessExpression: n := node.AsElementAccessExpression() - return (boolToByte(n.Expression != nil) << 0) | (boolToByte(n.QuestionDotToken != nil) << 1) | (boolToByte(n.ArgumentExpression != nil) << 2) + return (boolToByte(n.Expression() != nil) << 0) | (boolToByte(n.QuestionDotToken() != nil) << 1) | (boolToByte(n.ArgumentExpression() != nil) << 2) case ast.KindCallExpression: n := node.AsCallExpression() - return (boolToByte(n.Expression != nil) << 0) | (boolToByte(n.QuestionDotToken != nil) << 1) | (boolToByte(n.TypeArguments != nil) << 2) | (boolToByte(n.Arguments != nil) << 3) + return (boolToByte(n.Expression() != nil) << 0) | (boolToByte(n.QuestionDotToken() != nil) << 1) | (boolToByte(n.TypeArguments() != nil) << 2) | (boolToByte(n.Arguments() != nil) << 3) case ast.KindNewExpression: n := node.AsNewExpression() - return (boolToByte(n.Expression != nil) << 0) | (boolToByte(n.TypeArguments != nil) << 1) | (boolToByte(n.Arguments != nil) << 2) + return (boolToByte(n.Expression() != nil) << 0) | (boolToByte(n.TypeArguments() != nil) << 1) | (boolToByte(n.Arguments() != nil) << 2) case ast.KindMetaProperty: n := node.AsMetaProperty() return (boolToByte(n.Name() != nil) << 0) case ast.KindNonNullExpression: n := node.AsNonNullExpression() - return (boolToByte(n.Expression != nil) << 0) + return (boolToByte(n.Expression() != nil) << 0) case ast.KindSpreadElement: n := node.AsSpreadElement() - return (boolToByte(n.Expression != nil) << 0) + return (boolToByte(n.Expression() != nil) << 0) case ast.KindTemplateExpression: n := node.AsTemplateExpression() - return (boolToByte(n.Head != nil) << 0) | (boolToByte(n.TemplateSpans != nil) << 1) + return (boolToByte(n.Head() != nil) << 0) | (boolToByte(n.TemplateSpans() != nil) << 1) case ast.KindTemplateSpan: n := node.AsTemplateSpan() - return (boolToByte(n.Expression != nil) << 0) | (boolToByte(n.Literal != nil) << 1) + return (boolToByte(n.Expression() != nil) << 0) | (boolToByte(n.Literal() != nil) << 1) case ast.KindTaggedTemplateExpression: n := node.AsTaggedTemplateExpression() - return (boolToByte(n.Tag != nil) << 0) | (boolToByte(n.QuestionDotToken != nil) << 1) | (boolToByte(n.TypeArguments != nil) << 2) | (boolToByte(n.Template != nil) << 3) + return (boolToByte(n.Tag() != nil) << 0) | (boolToByte(n.QuestionDotToken() != nil) << 1) | (boolToByte(n.TypeArguments() != nil) << 2) | (boolToByte(n.Template() != nil) << 3) case ast.KindParenthesizedExpression: n := node.AsParenthesizedExpression() - return (boolToByte(n.Expression != nil) << 0) + return (boolToByte(n.Expression() != nil) << 0) case ast.KindArrayLiteralExpression: n := node.AsArrayLiteralExpression() - return (boolToByte(n.Elements != nil) << 0) + return (boolToByte(n.Elements() != nil) << 0) case ast.KindObjectLiteralExpression: n := node.AsObjectLiteralExpression() - return (boolToByte(n.Properties != nil) << 0) + return (boolToByte(n.Properties() != nil) << 0) case ast.KindSpreadAssignment: n := node.AsSpreadAssignment() - return (boolToByte(n.Expression != nil) << 0) + return (boolToByte(n.Expression() != nil) << 0) case ast.KindPropertyAssignment: n := node.AsPropertyAssignment() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.PostfixToken != nil) << 2) | (boolToByte(n.Type != nil) << 3) | (boolToByte(n.Initializer != nil) << 4) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.PostfixToken() != nil) << 2) | (boolToByte(n.Type() != nil) << 3) | (boolToByte(n.Initializer() != nil) << 4) case ast.KindShorthandPropertyAssignment: n := node.AsShorthandPropertyAssignment() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.PostfixToken != nil) << 2) | (boolToByte(n.Type != nil) << 3) | (boolToByte(n.EqualsToken != nil) << 4) | (boolToByte(n.ObjectAssignmentInitializer != nil) << 5) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.PostfixToken() != nil) << 2) | (boolToByte(n.Type() != nil) << 3) | (boolToByte(n.EqualsToken() != nil) << 4) | (boolToByte(n.ObjectAssignmentInitializer() != nil) << 5) case ast.KindDeleteExpression: n := node.AsDeleteExpression() - return (boolToByte(n.Expression != nil) << 0) + return (boolToByte(n.Expression() != nil) << 0) case ast.KindTypeOfExpression: n := node.AsTypeOfExpression() - return (boolToByte(n.Expression != nil) << 0) + return (boolToByte(n.Expression() != nil) << 0) case ast.KindVoidExpression: n := node.AsVoidExpression() - return (boolToByte(n.Expression != nil) << 0) + return (boolToByte(n.Expression() != nil) << 0) case ast.KindAwaitExpression: n := node.AsAwaitExpression() - return (boolToByte(n.Expression != nil) << 0) + return (boolToByte(n.Expression() != nil) << 0) case ast.KindTypeAssertionExpression: n := node.AsTypeAssertion() - return (boolToByte(n.Type != nil) << 0) | (boolToByte(n.Expression != nil) << 1) + return (boolToByte(n.Type() != nil) << 0) | (boolToByte(n.Expression() != nil) << 1) case ast.KindUnionType: n := node.AsUnionTypeNode() - return (boolToByte(n.Types != nil) << 0) + return (boolToByte(n.Types() != nil) << 0) case ast.KindIntersectionType: n := node.AsIntersectionTypeNode() - return (boolToByte(n.Types != nil) << 0) + return (boolToByte(n.Types() != nil) << 0) case ast.KindConditionalType: n := node.AsConditionalTypeNode() - return (boolToByte(n.CheckType != nil) << 0) | (boolToByte(n.ExtendsType != nil) << 1) | (boolToByte(n.TrueType != nil) << 2) | (boolToByte(n.FalseType != nil) << 3) + return (boolToByte(n.CheckType() != nil) << 0) | (boolToByte(n.ExtendsType() != nil) << 1) | (boolToByte(n.TrueType() != nil) << 2) | (boolToByte(n.FalseType() != nil) << 3) case ast.KindTypeOperator: n := node.AsTypeOperatorNode() - return (boolToByte(n.Type != nil) << 0) + return (boolToByte(n.Type() != nil) << 0) case ast.KindInferType: n := node.AsInferTypeNode() - return (boolToByte(n.TypeParameter != nil) << 0) + return (boolToByte(n.TypeParameter() != nil) << 0) case ast.KindArrayType: n := node.AsArrayTypeNode() - return (boolToByte(n.ElementType != nil) << 0) + return (boolToByte(n.ElementType() != nil) << 0) case ast.KindIndexedAccessType: n := node.AsIndexedAccessTypeNode() - return (boolToByte(n.ObjectType != nil) << 0) | (boolToByte(n.IndexType != nil) << 1) + return (boolToByte(n.ObjectType() != nil) << 0) | (boolToByte(n.IndexType() != nil) << 1) case ast.KindTypeReference: n := node.AsTypeReferenceNode() - return (boolToByte(n.TypeName != nil) << 0) | (boolToByte(n.TypeArguments != nil) << 1) + return (boolToByte(n.TypeName() != nil) << 0) | (boolToByte(n.TypeArguments() != nil) << 1) case ast.KindExpressionWithTypeArguments: n := node.AsExpressionWithTypeArguments() - return (boolToByte(n.Expression != nil) << 0) | (boolToByte(n.TypeArguments != nil) << 1) + return (boolToByte(n.Expression() != nil) << 0) | (boolToByte(n.TypeArguments() != nil) << 1) case ast.KindLiteralType: n := node.AsLiteralTypeNode() - return (boolToByte(n.Literal != nil) << 0) + return (boolToByte(n.Literal() != nil) << 0) case ast.KindTypePredicate: n := node.AsTypePredicateNode() - return (boolToByte(n.AssertsModifier != nil) << 0) | (boolToByte(n.ParameterName != nil) << 1) | (boolToByte(n.Type != nil) << 2) + return (boolToByte(n.AssertsModifier() != nil) << 0) | (boolToByte(n.ParameterName() != nil) << 1) | (boolToByte(n.Type() != nil) << 2) case ast.KindImportAttribute: n := node.AsImportAttribute() - return (boolToByte(n.Name() != nil) << 0) | (boolToByte(n.Value != nil) << 1) + return (boolToByte(n.Name() != nil) << 0) | (boolToByte(n.Value() != nil) << 1) case ast.KindImportAttributes: n := node.AsImportAttributes() - return (boolToByte(n.Attributes != nil) << 0) + return (boolToByte(n.Attributes() != nil) << 0) case ast.KindTypeQuery: n := node.AsTypeQueryNode() - return (boolToByte(n.ExprName != nil) << 0) | (boolToByte(n.TypeArguments != nil) << 1) + return (boolToByte(n.ExprName() != nil) << 0) | (boolToByte(n.TypeArguments() != nil) << 1) case ast.KindMappedType: n := node.AsMappedTypeNode() - return (boolToByte(n.ReadonlyToken != nil) << 0) | (boolToByte(n.TypeParameter != nil) << 1) | (boolToByte(n.NameType != nil) << 2) | (boolToByte(n.QuestionToken != nil) << 3) | (boolToByte(n.Type != nil) << 4) | (boolToByte(n.Members != nil) << 5) + return (boolToByte(n.ReadonlyToken() != nil) << 0) | (boolToByte(n.TypeParameter() != nil) << 1) | (boolToByte(n.NameType() != nil) << 2) | (boolToByte(n.QuestionToken() != nil) << 3) | (boolToByte(n.Type() != nil) << 4) | (boolToByte(n.Members() != nil) << 5) case ast.KindTypeLiteral: n := node.AsTypeLiteralNode() - return (boolToByte(n.Members != nil) << 0) + return (boolToByte(n.Members() != nil) << 0) case ast.KindTupleType: n := node.AsTupleTypeNode() - return (boolToByte(n.Elements != nil) << 0) + return (boolToByte(n.Elements() != nil) << 0) case ast.KindNamedTupleMember: n := node.AsNamedTupleMember() - return (boolToByte(n.DotDotDotToken != nil) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.QuestionToken != nil) << 2) | (boolToByte(n.Type != nil) << 3) + return (boolToByte(n.DotDotDotToken() != nil) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.QuestionToken() != nil) << 2) | (boolToByte(n.Type() != nil) << 3) case ast.KindOptionalType: n := node.AsOptionalTypeNode() - return (boolToByte(n.Type != nil) << 0) + return (boolToByte(n.Type() != nil) << 0) case ast.KindRestType: n := node.AsRestTypeNode() - return (boolToByte(n.Type != nil) << 0) + return (boolToByte(n.Type() != nil) << 0) case ast.KindParenthesizedType: n := node.AsParenthesizedTypeNode() - return (boolToByte(n.Type != nil) << 0) + return (boolToByte(n.Type() != nil) << 0) case ast.KindFunctionType: n := node.AsFunctionTypeNode() - return (boolToByte(n.TypeParameters != nil) << 0) | (boolToByte(n.Parameters != nil) << 1) | (boolToByte(n.Type != nil) << 2) + return (boolToByte(n.TypeParameters() != nil) << 0) | (boolToByte(n.Parameters() != nil) << 1) | (boolToByte(n.Type() != nil) << 2) case ast.KindConstructorType: n := node.AsConstructorTypeNode() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.TypeParameters != nil) << 1) | (boolToByte(n.Parameters != nil) << 2) | (boolToByte(n.Type != nil) << 3) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.TypeParameters() != nil) << 1) | (boolToByte(n.Parameters() != nil) << 2) | (boolToByte(n.Type() != nil) << 3) case ast.KindTemplateLiteralType: n := node.AsTemplateLiteralTypeNode() - return (boolToByte(n.Head != nil) << 0) | (boolToByte(n.TemplateSpans != nil) << 1) + return (boolToByte(n.Head() != nil) << 0) | (boolToByte(n.TemplateSpans() != nil) << 1) case ast.KindTemplateLiteralTypeSpan: n := node.AsTemplateLiteralTypeSpan() - return (boolToByte(n.Type != nil) << 0) | (boolToByte(n.Literal != nil) << 1) + return (boolToByte(n.Type() != nil) << 0) | (boolToByte(n.Literal() != nil) << 1) case ast.KindSyntheticExpression: n := node.AsSyntheticExpression() - return (boolToByte(n.TupleNameSource != nil) << 0) + return (boolToByte(n.TupleNameSource() != nil) << 0) case ast.KindPartiallyEmittedExpression: n := node.AsPartiallyEmittedExpression() - return (boolToByte(n.Expression != nil) << 0) + return (boolToByte(n.Expression() != nil) << 0) case ast.KindJsxElement: n := node.AsJsxElement() - return (boolToByte(n.OpeningElement != nil) << 0) | (boolToByte(n.Children != nil) << 1) | (boolToByte(n.ClosingElement != nil) << 2) + return (boolToByte(n.OpeningElement() != nil) << 0) | (boolToByte(n.Children() != nil) << 1) | (boolToByte(n.ClosingElement() != nil) << 2) case ast.KindJsxAttributes: n := node.AsJsxAttributes() - return (boolToByte(n.Properties != nil) << 0) + return (boolToByte(n.Properties() != nil) << 0) case ast.KindJsxNamespacedName: n := node.AsJsxNamespacedName() - return (boolToByte(n.Namespace != nil) << 0) | (boolToByte(n.Name() != nil) << 1) + return (boolToByte(n.Namespace() != nil) << 0) | (boolToByte(n.Name() != nil) << 1) case ast.KindJsxOpeningElement: n := node.AsJsxOpeningElement() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.TypeArguments != nil) << 1) | (boolToByte(n.Attributes != nil) << 2) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.TypeArguments() != nil) << 1) | (boolToByte(n.Attributes() != nil) << 2) case ast.KindJsxSelfClosingElement: n := node.AsJsxSelfClosingElement() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.TypeArguments != nil) << 1) | (boolToByte(n.Attributes != nil) << 2) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.TypeArguments() != nil) << 1) | (boolToByte(n.Attributes() != nil) << 2) case ast.KindJsxFragment: n := node.AsJsxFragment() - return (boolToByte(n.OpeningFragment != nil) << 0) | (boolToByte(n.Children != nil) << 1) | (boolToByte(n.ClosingFragment != nil) << 2) + return (boolToByte(n.OpeningFragment() != nil) << 0) | (boolToByte(n.Children() != nil) << 1) | (boolToByte(n.ClosingFragment() != nil) << 2) case ast.KindJsxAttribute: n := node.AsJsxAttribute() - return (boolToByte(n.Name() != nil) << 0) | (boolToByte(n.Initializer != nil) << 1) + return (boolToByte(n.Name() != nil) << 0) | (boolToByte(n.Initializer() != nil) << 1) case ast.KindJsxSpreadAttribute: n := node.AsJsxSpreadAttribute() - return (boolToByte(n.Expression != nil) << 0) + return (boolToByte(n.Expression() != nil) << 0) case ast.KindJsxClosingElement: n := node.AsJsxClosingElement() - return (boolToByte(n.TagName != nil) << 0) + return (boolToByte(n.TagName() != nil) << 0) case ast.KindJsxExpression: n := node.AsJsxExpression() - return (boolToByte(n.DotDotDotToken != nil) << 0) | (boolToByte(n.Expression != nil) << 1) + return (boolToByte(n.DotDotDotToken() != nil) << 0) | (boolToByte(n.Expression() != nil) << 1) case ast.KindSyntaxList: n := node.AsSyntaxList() return (boolToByte(len(n.Children) > 0) << 0) case ast.KindJSDoc: n := node.AsJSDoc() - return (boolToByte(n.Comment != nil) << 0) | (boolToByte(n.Tags != nil) << 1) + return (boolToByte(n.Comment() != nil) << 0) | (boolToByte(n.Tags() != nil) << 1) case ast.KindJSDocTypeExpression: n := node.AsJSDocTypeExpression() - return (boolToByte(n.Type != nil) << 0) + return (boolToByte(n.Type() != nil) << 0) case ast.KindJSDocNonNullableType: n := node.AsJSDocNonNullableType() - return (boolToByte(n.Type != nil) << 0) + return (boolToByte(n.Type() != nil) << 0) case ast.KindJSDocNullableType: n := node.AsJSDocNullableType() - return (boolToByte(n.Type != nil) << 0) + return (boolToByte(n.Type() != nil) << 0) case ast.KindJSDocVariadicType: n := node.AsJSDocVariadicType() - return (boolToByte(n.Type != nil) << 0) + return (boolToByte(n.Type() != nil) << 0) case ast.KindJSDocOptionalType: n := node.AsJSDocOptionalType() - return (boolToByte(n.Type != nil) << 0) + return (boolToByte(n.Type() != nil) << 0) case ast.KindJSDocTypeTag: n := node.AsJSDocTypeTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.TypeExpression != nil) << 1) | (boolToByte(n.Comment != nil) << 2) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.TypeExpression() != nil) << 1) | (boolToByte(n.Comment() != nil) << 2) case ast.KindJSDocUnknownTag: n := node.AsJSDocUnknownTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.Comment != nil) << 1) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.Comment() != nil) << 1) case ast.KindJSDocTemplateTag: n := node.AsJSDocTemplateTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.Constraint != nil) << 1) | (boolToByte(n.TypeParameters != nil) << 2) | (boolToByte(n.Comment != nil) << 3) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.Constraint() != nil) << 1) | (boolToByte(n.TypeParameters() != nil) << 2) | (boolToByte(n.Comment() != nil) << 3) case ast.KindJSDocReturnTag: n := node.AsJSDocReturnTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.TypeExpression != nil) << 1) | (boolToByte(n.Comment != nil) << 2) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.TypeExpression() != nil) << 1) | (boolToByte(n.Comment() != nil) << 2) case ast.KindJSDocPublicTag: n := node.AsJSDocPublicTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.Comment != nil) << 1) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.Comment() != nil) << 1) case ast.KindJSDocPrivateTag: n := node.AsJSDocPrivateTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.Comment != nil) << 1) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.Comment() != nil) << 1) case ast.KindJSDocProtectedTag: n := node.AsJSDocProtectedTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.Comment != nil) << 1) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.Comment() != nil) << 1) case ast.KindJSDocReadonlyTag: n := node.AsJSDocReadonlyTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.Comment != nil) << 1) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.Comment() != nil) << 1) case ast.KindJSDocOverrideTag: n := node.AsJSDocOverrideTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.Comment != nil) << 1) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.Comment() != nil) << 1) case ast.KindJSDocDeprecatedTag: n := node.AsJSDocDeprecatedTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.Comment != nil) << 1) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.Comment() != nil) << 1) case ast.KindJSDocSeeTag: n := node.AsJSDocSeeTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.NameExpression != nil) << 1) | (boolToByte(n.Comment != nil) << 2) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.NameExpression() != nil) << 1) | (boolToByte(n.Comment() != nil) << 2) case ast.KindJSDocImplementsTag: n := node.AsJSDocImplementsTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.ClassName != nil) << 1) | (boolToByte(n.Comment != nil) << 2) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.ClassName() != nil) << 1) | (boolToByte(n.Comment() != nil) << 2) case ast.KindJSDocAugmentsTag: n := node.AsJSDocAugmentsTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.ClassName != nil) << 1) | (boolToByte(n.Comment != nil) << 2) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.ClassName() != nil) << 1) | (boolToByte(n.Comment() != nil) << 2) case ast.KindJSDocSatisfiesTag: n := node.AsJSDocSatisfiesTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.TypeExpression != nil) << 1) | (boolToByte(n.Comment != nil) << 2) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.TypeExpression() != nil) << 1) | (boolToByte(n.Comment() != nil) << 2) case ast.KindJSDocThrowsTag: n := node.AsJSDocThrowsTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.TypeExpression != nil) << 1) | (boolToByte(n.Comment != nil) << 2) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.TypeExpression() != nil) << 1) | (boolToByte(n.Comment() != nil) << 2) case ast.KindJSDocThisTag: n := node.AsJSDocThisTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.TypeExpression != nil) << 1) | (boolToByte(n.Comment != nil) << 2) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.TypeExpression() != nil) << 1) | (boolToByte(n.Comment() != nil) << 2) case ast.KindJSDocImportTag: n := node.AsJSDocImportTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.ImportClause != nil) << 1) | (boolToByte(n.ModuleSpecifier != nil) << 2) | (boolToByte(n.Attributes != nil) << 3) | (boolToByte(n.Comment != nil) << 4) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.ImportClause() != nil) << 1) | (boolToByte(n.ModuleSpecifier() != nil) << 2) | (boolToByte(n.Attributes() != nil) << 3) | (boolToByte(n.Comment() != nil) << 4) case ast.KindJSDocCallbackTag: n := node.AsJSDocCallbackTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.TypeExpression != nil) << 1) | (boolToByte(n.Name() != nil) << 2) | (boolToByte(n.Comment != nil) << 3) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.TypeExpression() != nil) << 1) | (boolToByte(n.Name() != nil) << 2) | (boolToByte(n.Comment() != nil) << 3) case ast.KindJSDocOverloadTag: n := node.AsJSDocOverloadTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.TypeExpression != nil) << 1) | (boolToByte(n.Comment != nil) << 2) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.TypeExpression() != nil) << 1) | (boolToByte(n.Comment() != nil) << 2) case ast.KindJSDocTypedefTag: n := node.AsJSDocTypedefTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.TypeExpression != nil) << 1) | (boolToByte(n.Name() != nil) << 2) | (boolToByte(n.Comment != nil) << 3) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.TypeExpression() != nil) << 1) | (boolToByte(n.Name() != nil) << 2) | (boolToByte(n.Comment() != nil) << 3) case ast.KindJSDocSignature: n := node.AsJSDocSignature() - return (boolToByte(n.TypeParameters != nil) << 0) | (boolToByte(n.Parameters != nil) << 1) | (boolToByte(n.Type != nil) << 2) + return (boolToByte(n.TypeParameters() != nil) << 0) | (boolToByte(n.Parameters() != nil) << 1) | (boolToByte(n.Type() != nil) << 2) case ast.KindJSDocNameReference: n := node.AsJSDocNameReference() return (boolToByte(n.Name() != nil) << 0) case ast.KindModuleDeclaration: n := node.AsModuleDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.Attributes != nil) << 2) | (boolToByte(n.Body != nil) << 3) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.Attributes() != nil) << 2) | (boolToByte(n.Body() != nil) << 3) case ast.KindImportEqualsDeclaration: n := node.AsImportEqualsDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.ModuleReference != nil) << 2) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.ModuleReference() != nil) << 2) case ast.KindExportDeclaration: n := node.AsExportDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.ExportClause != nil) << 1) | (boolToByte(n.ModuleSpecifier != nil) << 2) | (boolToByte(n.Attributes != nil) << 3) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.ExportClause() != nil) << 1) | (boolToByte(n.ModuleSpecifier() != nil) << 2) | (boolToByte(n.Attributes() != nil) << 3) case ast.KindImportType: n := node.AsImportTypeNode() - return (boolToByte(n.Argument != nil) << 0) | (boolToByte(n.Attributes != nil) << 1) | (boolToByte(n.Qualifier != nil) << 2) | (boolToByte(n.TypeArguments != nil) << 3) + return (boolToByte(n.Argument() != nil) << 0) | (boolToByte(n.Attributes() != nil) << 1) | (boolToByte(n.Qualifier() != nil) << 2) | (boolToByte(n.TypeArguments() != nil) << 3) case ast.KindImportClause: n := node.AsImportClause() - return (boolToByte(n.Name() != nil) << 0) | (boolToByte(n.NamedBindings != nil) << 1) + return (boolToByte(n.Name() != nil) << 0) | (boolToByte(n.NamedBindings() != nil) << 1) case ast.KindImportSpecifier: n := node.AsImportSpecifier() - return (boolToByte(n.PropertyName != nil) << 0) | (boolToByte(n.Name() != nil) << 1) + return (boolToByte(n.PropertyName() != nil) << 0) | (boolToByte(n.Name() != nil) << 1) case ast.KindJSDocLink: n := node.AsJSDocLink() return (boolToByte(n.Name() != nil) << 0) @@ -523,16 +523,16 @@ func getChildrenPropertyMask(node *ast.Node) uint8 { return (boolToByte(n.Name() != nil) << 0) case ast.KindTypeParameter: n := node.AsTypeParameterDeclaration() - return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.Constraint != nil) << 2) | (boolToByte(n.Expression != nil) << 3) | (boolToByte(n.DefaultType != nil) << 4) + return (boolToByte(hasModifiers(n.Modifiers())) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.Constraint() != nil) << 2) | (boolToByte(n.Expression() != nil) << 3) | (boolToByte(n.DefaultType() != nil) << 4) case ast.KindSyntheticReferenceExpression: n := node.AsSyntheticReferenceExpression() - return (boolToByte(n.Expression != nil) << 0) | (boolToByte(n.ThisArg != nil) << 1) + return (boolToByte(n.Expression() != nil) << 0) | (boolToByte(n.ThisArg() != nil) << 1) case ast.KindJSDocTypeLiteral: n := node.AsJSDocTypeLiteral() return (boolToByte(len(n.JSDocPropertyTags) > 0) << 0) case ast.KindJSDocParameterTag, ast.KindJSDocPropertyTag: n := node.AsJSDocParameterOrPropertyTag() - return (boolToByte(n.TagName != nil) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.TypeExpression != nil) << 2) | (boolToByte(n.Comment != nil) << 3) + return (boolToByte(n.TagName() != nil) << 0) | (boolToByte(n.Name() != nil) << 1) | (boolToByte(n.TypeExpression() != nil) << 2) | (boolToByte(n.Comment() != nil) << 3) default: return 0 } diff --git a/tsc/internal/ast/arena.go b/tsc/internal/ast/arena.go new file mode 100644 index 0000000000000..fed5f5d98f101 --- /dev/null +++ b/tsc/internal/ast/arena.go @@ -0,0 +1,262 @@ +package ast + +import ( + "unsafe" + + "github.com/microsoft/TypeScript/tsc/internal/linkarena" +) + +// Nodes and node lists are allocated from arenas (see package linkarena) and refer to each +// other through 32-bit links. The garbage collector does not look inside arena memory, so +// what a node holds is kept alive in other ways: +// +// - Links and the Parent pointer go through accessors, which record when a node refers to +// a node of another factory. +// - Strings and slices passed to a NodeFactory are registered with its arena. +// - Any other pointer to a Go object that is stored in a node (a symbol, a flow node, a +// symbol table) must be registered by whoever stores it; see KeepAlive. +// +// The exceptions are SourceFile nodes, the synthetic nodes of flow analysis and any Node +// that was not created by a NodeFactory. Those are ordinary Go objects, which cannot be the +// target of a link. + +// link refers to a T in arena memory. It is 4 bytes wide. +type link[T any] struct { + l linkarena.Link +} + +func (l link[T]) get() *T { + return (*T)(linkarena.At(l.l)) +} + +// set makes the link refer to p. The link itself and p must be in arena memory. +func (l *link[T]) set(p *T) { + l.l = linkarena.LinkTo(unsafe.Pointer(l), unsafe.Pointer(p)) +} + +// arena returns the arena the node was allocated from, or nil for a node that is an +// ordinary Go object. +func (n *Node) arena() *linkarena.Arena { + if !n.inArena { + return nil + } + return linkarena.Of(unsafe.Pointer(n)) +} + +// Parent returns the node's parent. +func (n *Node) Parent() *Node { + return n.parent +} + +// SetParent sets the node's parent. +func (n *Node) SetParent(parent *Node) { + n.parent = parent + if parent != nil { + n.refersTo(parent) + } +} + +// refersTo records that the node's memory holds a pointer to target. +func (n *Node) refersTo(target *Node) { + if !n.inArena { + // The collector sees what an ordinary Go object points to. + return + } + if !target.inArena { + linkarena.Of(unsafe.Pointer(n)).Keep(unsafe.Pointer(target), unsafe.Sizeof(*target)) + return + } + linkarena.Refer(unsafe.Pointer(n), unsafe.Pointer(target)) +} + +// KeepAlive keeps the Go object p points to alive for as long as node. It must be called +// when a pointer to a Go object is stored in a field of node or of its data, because the +// garbage collector does not see such pointers. +func KeepAlive[T any](node *Node, p *T) { + if p == nil { + return + } + if a := node.arena(); a != nil { + a.Keep(unsafe.Pointer(p), unsafe.Sizeof(*p)) + } +} + +// SetSymbol stores a symbol in a declaration node that was not created by the parser. (The +// binder keeps the symbols it gives to parsed nodes alive as a whole.) +func SetSymbol(node *Node, symbol *Symbol) { + node.DeclarationData().Symbol = symbol + KeepAlive(node, symbol) +} + +// SetFlowNode stores a flow node in a node that was not created by the parser. +func SetFlowNode(node *Node, flowNode *FlowNode) { + node.FlowNodeData().FlowNode = flowNode + KeepAlive(node, flowNode) +} + +// SetLocals stores a symbol table in a node that can have locals. +func SetLocals(container *Node, locals SymbolTable) { + container.LocalsContainerData().Locals = locals + keepSymbolTable(container, locals) +} + +func keepSymbolTable(holder *Node, table SymbolTable) { + if table == nil { + return + } + if a := holder.arena(); a != nil { + // A map value is a pointer to the map. + a.Keep(*(*unsafe.Pointer)(unsafe.Pointer(&table)), 1) + } +} + +// mem returns the arena the factory allocates from. +func (f *NodeFactory) mem() *linkarena.Arena { + if f.arena == nil { + f.arena = linkarena.NewArena(0) + } + return f.arena +} + +// newParseArena returns an arena for nodes parsed from sourceText. The arena keeps the text +// alive, so that the many strings that are slices of it need no registration of their own. +func newParseArena(sourceText string, sizeHint int) *linkarena.Arena { + arena := linkarena.NewArena(sizeHint) + if len(sourceText) != 0 { + arena.Keep(unsafe.Pointer(unsafe.StringData(sourceText)), uintptr(len(sourceText))) + } + return arena +} + +// StartParse readies the factory for building the syntax tree of sourceText in a new arena. +// Until the factory is reset, every node placed in a node list must have been created by it. +func (f *NodeFactory) StartParse(sourceText string) { + // A syntax tree takes several times the size of its text. A low estimate costs little: + // the arena grows in small steps once the estimate is used up. + f.arena = newParseArena(sourceText, len(sourceText)*5) + f.parsing = true + f.sourceText = sourceText +} + +// StartLazyJSDocParse readies the factory for parsing a JSDoc comment of file on demand. +// All such comments of a file share one arena; a comment is far smaller than the smallest +// arena. The caller holds the lock that guards the file's JSDoc cache. +func (f *NodeFactory) StartLazyJSDocParse(file *SourceFile) { + if file.lazyJSDocArena == nil { + file.lazyJSDocArena = newParseArena(file.text, 0) + } + f.arena = file.lazyJSDocArena + f.parsing = true + f.sourceText = file.text +} + +// Factories that are reset after each use keep allocating from the same arena until it has +// reached this size. A node that outlives its factory's reset keeps its whole arena alive, +// so starting a new arena for every use would cost a chunk for each such node, and keeping +// one arena forever would never release anything. +const maxReusedArenaSize = 64 << 10 + +// ReleaseArenas resets the factory so that the nodes it created can be collected once +// nothing refers to them. +func (f *NodeFactory) ReleaseArenas() { + f.VerifyArena() + arena := f.arena + if arena != nil && arena.Size() >= maxReusedArenaSize { + arena = nil + } + *f = NodeFactory{ + hooks: f.hooks, + arena: arena, + textCount: f.textCount, + nodeCount: f.nodeCount, + } +} + +func newData[T any](f *NodeFactory) *T { + return linkarena.New[T](f.mem()) +} + +// NewNodeSlice returns a slice for the elements of a node list created by this factory. +func (f *NodeFactory) NewNodeSlice(length int) []*Node { + return linkarena.MakeSlice[*Node](f.mem(), length, length) +} + +// keepString registers the data of a string stored in a node of the factory. +func (f *NodeFactory) keepString(s string) { + if len(s) == 0 { + return + } + data := unsafe.StringData(s) + if uintptr(unsafe.Pointer(data))-uintptr(unsafe.Pointer(unsafe.StringData(f.sourceText))) < uintptr(len(f.sourceText)) { + return + } + f.mem().Keep(unsafe.Pointer(data), uintptr(len(s))) +} + +// keepSlice registers the backing array of a slice stored in a node of the factory. The +// array is an ordinary Go object, so the collector sees what its elements point to. +func keepSlice[T any](f *NodeFactory, s []T) { + linkarena.KeepSlice(f.mem(), s) +} + +// keepValue registers the object behind an interface value stored in a node of the factory. +func (f *NodeFactory) keepValue(v any) { + if v != nil { + // The second word of an interface value points to its data. + f.mem().Keep((*[2]unsafe.Pointer)(unsafe.Pointer(&v))[1], 1) + } +} + +// keepNodes registers a slice of nodes stored in arena memory. +func (f *NodeFactory) keepNodes(nodes []*Node) { + adoptNodes(f.mem(), nodes, f.parsing) +} + +// adoptNodes makes arena keep alive what a slice of nodes, stored in the arena's memory, +// refers to. sameArena states that the nodes are known to belong to the arena. +func adoptNodes(arena *linkarena.Arena, nodes []*Node, sameArena bool) { + if cap(nodes) == 0 { + return + } + if !arena.Contains(unsafe.Pointer(unsafe.SliceData(nodes))) { + // The backing array is an ordinary Go object: the collector sees its elements. + linkarena.KeepSlice(arena, nodes) + return + } + if sameArena { + return + } + for _, node := range nodes { + if node == nil { + continue + } + if !node.inArena { + arena.Keep(unsafe.Pointer(node), unsafe.Sizeof(*node)) + } else { + arena.Use(unsafe.Pointer(node)) + } + } +} + +// SetNodes replaces the elements of the list. +func (list *NodeList) SetNodes(nodes []*Node) { + list.Nodes = nodes + adoptNodes(linkarena.Of(unsafe.Pointer(list)), nodes, false) +} + +// VerifyArena checks, when verification is on (see package linkarena), that everything the +// nodes created by the factory refer to is kept alive, and panics otherwise. +func (f *NodeFactory) VerifyArena() { + if f.arena != nil { + verifyArena(f.arena, "a node factory") + } +} + +func verifyArena(arena *linkarena.Arena, owner string) { + if !linkarena.Verifying() { + return + } + if violations := arena.Verify(8); len(violations) != 0 { + panic("nodes of " + owner + " refer to memory that is not kept alive:" + linkarena.FormatViolations(violations)) + } +} diff --git a/tsc/internal/ast/arena_test.go b/tsc/internal/ast/arena_test.go new file mode 100644 index 0000000000000..321a76324f85f --- /dev/null +++ b/tsc/internal/ast/arena_test.go @@ -0,0 +1,125 @@ +package ast_test + +import ( + "runtime" + "strings" + "testing" + + "github.com/microsoft/TypeScript/tsc/internal/ast" + "github.com/microsoft/TypeScript/tsc/internal/testutil/parsetestutil" + "gotest.tools/v3/assert" +) + +// churn runs the collector and reuses whatever memory it released. +func churn() { + for range 3 { + runtime.GC() + } + garbage := make([][]byte, 0, 4096) + for range cap(garbage) { + garbage = append(garbage, []byte(strings.Repeat("x", 4096))) + } + runtime.KeepAlive(garbage) + runtime.GC() +} + +func findIdentifier(node *ast.Node, text string) *ast.Node { + if ast.IsIdentifier(node) && node.Text() == text { + return node + } + var found *ast.Node + node.ForEachChild(func(child *ast.Node) bool { + found = findIdentifier(child, text) + return found != nil + }) + return found +} + +//go:noinline +func parseAndFind(source string, text string) *ast.Node { + return findIdentifier(parsetestutil.ParseTypeScript(source, false).AsNode(), text) +} + +// The collector does not look inside nodes, so everything a node refers to has to be kept +// alive by the node's arena. +func TestNodeKeepsItsTreeAlive(t *testing.T) { + t.Parallel() + var source strings.Builder + for i := range 2000 { + source.WriteString("function f") + source.WriteRune(rune('a' + i%26)) + source.WriteString("() { return [1, 2, 3].map(x => x + 1); }\n") + } + source.WriteString("const needle = { first: 1, second: [haystack] };\n") + + // Only a leaf of the tree is held. + leaf := parseAndFind(source.String(), "haystack") + churn() + + assert.Equal(t, leaf.Text(), "haystack") + array := leaf.Parent() + assert.Equal(t, array.Kind, ast.KindArrayLiteralExpression) + property := array.Parent() + assert.Equal(t, property.Name().Text(), "second") + object := property.Parent() + assert.Equal(t, len(object.Properties()), 2) + assert.Equal(t, object.Properties()[0].Name().Text(), "first") + root := leaf + for root.Parent() != nil { + root = root.Parent() + } + file := root.AsSourceFile() + assert.Equal(t, file.Text(), source.String()) + assert.Equal(t, len(file.Statements.Nodes), 2001) + assert.Equal(t, file.Statements.Nodes[0].Name().Text(), "fa") +} + +//go:noinline +func combine(factory *ast.NodeFactory, name string) *ast.Node { + // A parsed node stored in a slice of a new list, and one linked to directly. + listed := parseAndFind("const value = listed + other;", "listed") + linked := parseAndFind("const value = linked * 2;", "linked") + text := strings.Repeat(name, 2) // not part of any source text + call := factory.NewCallExpression(factory.NewIdentifier(text), nil, nil, factory.NewNodeList([]*ast.Node{listed.Parent()}), ast.NodeFlagsNone) + return factory.NewBinaryExpression(nil, call, nil, factory.NewToken(ast.KindPlusToken), linked.Parent()) +} + +func TestNodeKeepsNodesOfOtherFactoriesAlive(t *testing.T) { + t.Parallel() + factory := ast.NewNodeFactory(ast.NodeFactoryHooks{}) + node := combine(factory, "callee").AsBinaryExpression() + // Other uses of the factory must not disturb nodes it created earlier. + factory.ReleaseArenas() + for range 5000 { + factory.NewIdentifier("filler") + } + factory = nil + churn() + + call := node.Left() + assert.Equal(t, call.Kind, ast.KindCallExpression) + assert.Equal(t, call.Expression().Text(), "calleecallee") + listed := call.Arguments()[0].AsBinaryExpression() + assert.Equal(t, listed.Left().Text(), "listed") + assert.Equal(t, listed.Right().Text(), "other") + linked := node.Right().AsBinaryExpression() + assert.Equal(t, linked.Left().Text(), "linked") + assert.Equal(t, linked.OperatorToken().Kind, ast.KindAsteriskToken) + // The parsed nodes still belong to their own trees. + assert.Equal(t, ast.GetSourceFileOfNode(listed.AsNode()).Text(), "const value = listed + other;") + assert.Equal(t, ast.GetSourceFileOfNode(linked.AsNode()).Text(), "const value = linked * 2;") +} + +func TestSetParentAcrossFactories(t *testing.T) { + t.Parallel() + child := func() *ast.Node { + parent := parseAndFind("outer(inner);", "inner").Parent() + child := ast.NewNodeFactory(ast.NodeFactoryHooks{}).NewIdentifier("synthetic") + child.SetParent(parent) + return child + }() + churn() + assert.Equal(t, child.Parent().Kind, ast.KindCallExpression) + assert.Equal(t, child.Parent().Expression().Text(), "outer") + assert.Equal(t, ast.GetSourceFileOfNode(child).Text(), "outer(inner);") +} diff --git a/tsc/internal/ast/ast.go b/tsc/internal/ast/ast.go index 9b08428dd9d4a..e3e88c9cb7555 100644 --- a/tsc/internal/ast/ast.go +++ b/tsc/internal/ast/ast.go @@ -6,10 +6,12 @@ import ( "strings" "sync" "sync/atomic" + "unsafe" "github.com/microsoft/TypeScript/tsc/internal/collections" "github.com/microsoft/TypeScript/tsc/internal/core" "github.com/microsoft/TypeScript/tsc/internal/diagnostics" + "github.com/microsoft/TypeScript/tsc/internal/linkarena" "github.com/microsoft/TypeScript/tsc/internal/spanmap" "github.com/microsoft/TypeScript/tsc/internal/tspath" "github.com/zeebo/xxh3" @@ -85,6 +87,8 @@ func newNode(kind Kind, data nodeData, hooks NodeFactoryHooks) *Node { func (f *NodeFactory) newNode(kind Kind, data nodeData) *Node { f.nodeCount++ + // Set before the hooks run, which may store pointers in the node. + data.AsNode().inArena = true return newNode(kind, data, f.hooks) } @@ -122,14 +126,17 @@ func cloneNode(updated *Node, original *Node, hooks NodeFactoryHooks) *Node { // NodeList type NodeList struct { - Loc core.TextRange + Loc core.TextRange + // Assign through SetNodes: a list is arena memory, which the garbage collector does not + // scan (see arena.go). Nodes []*Node } func (f *NodeFactory) NewNodeList(nodes []*Node) *NodeList { - list := f.nodeListArena.New() + list := newData[NodeList](f) list.Loc = core.UndefinedTextRange() list.Nodes = nodes + f.keepNodes(nodes) return list } @@ -158,18 +165,20 @@ type ModifierList struct { } func (f *NodeFactory) NewModifierList(nodes []*Node) *ModifierList { - list := f.modifierListArena.New() + list := newData[ModifierList](f) list.Loc = core.UndefinedTextRange() list.Nodes = nodes list.ModifierFlags = ModifiersToFlags(nodes) + f.keepNodes(nodes) return list } func (list *ModifierList) Clone(f *NodeFactory) *ModifierList { - res := f.modifierListArena.New() + res := newData[ModifierList](f) res.Loc = list.Loc res.Nodes = list.Nodes res.ModifierFlags = list.ModifierFlags + f.keepNodes(list.Nodes) return res } @@ -178,12 +187,14 @@ func (list *ModifierList) Clone(f *NodeFactory) *ModifierList { // interface valued properties either store a true nil or a reference to a non-nil struct. type Node struct { - Kind Kind - Flags NodeFlags - Loc core.TextRange - id atomic.Uint64 - Parent *Node - data nodeData + Kind Kind + // Set for a node that is allocated from an arena rather than as an ordinary Go object. + inArena bool + Flags NodeFlags + Loc core.TextRange + id atomic.Uint64 + parent *Node // use Parent and SetParent + data nodeData } // Node accessors. Some accessors are implemented as methods on NodeData, others are implemented though @@ -214,7 +225,7 @@ func (n *Node) DeclarationData() *DeclarationBase { return n.data.Declar func (n *Node) ExportableData() *ExportableBase { return n.data.ExportableData() } func (n *Node) LocalsContainerData() *LocalsContainerBase { return n.data.LocalsContainerData() } func (n *Node) FunctionLikeData() *FunctionLikeBase { return n.data.FunctionLikeData() } -func (n *Node) ParameterList() *ParameterList { return n.data.FunctionLikeData().Parameters } +func (n *Node) ParameterList() *ParameterList { return n.data.FunctionLikeData().Parameters() } func (n *Node) Parameters() []*ParameterDeclarationNode { return n.ParameterList().Nodes } func (n *Node) ClassLikeData() *ClassLikeBase { return n.data.ClassLikeData() } func (n *Node) BodyData() *BodyBase { return n.data.BodyData() } @@ -265,7 +276,7 @@ func (n *Node) Locals() SymbolTable { func (n *Node) Body() *Node { data := n.BodyData() if data != nil { - return data.Body + return data.Body() } return nil } @@ -293,7 +304,7 @@ func (n *Node) Text() string { case KindTemplateTail: return n.AsTemplateTail().Text case KindJsxNamespacedName: - return n.AsJsxNamespacedName().Namespace.Text() + ":" + n.AsJsxNamespacedName().name.Text() + return n.AsJsxNamespacedName().Namespace().Text() + ":" + n.AsJsxNamespacedName().name.get().Text() case KindRegularExpressionLiteral: return n.AsRegularExpressionLiteral().Text case KindJSDocText: @@ -311,75 +322,75 @@ func (n *Node) Text() string { func (n *Node) Expression() *Node { switch n.Kind { case KindPropertyAccessExpression: - return n.AsPropertyAccessExpression().Expression + return n.AsPropertyAccessExpression().Expression() case KindElementAccessExpression: - return n.AsElementAccessExpression().Expression + return n.AsElementAccessExpression().Expression() case KindParenthesizedExpression: - return n.AsParenthesizedExpression().Expression + return n.AsParenthesizedExpression().Expression() case KindCallExpression: - return n.AsCallExpression().Expression + return n.AsCallExpression().Expression() case KindNewExpression: - return n.AsNewExpression().Expression + return n.AsNewExpression().Expression() case KindExpressionWithTypeArguments: - return n.AsExpressionWithTypeArguments().Expression + return n.AsExpressionWithTypeArguments().Expression() case KindComputedPropertyName: - return n.AsComputedPropertyName().Expression + return n.AsComputedPropertyName().Expression() case KindNonNullExpression: - return n.AsNonNullExpression().Expression + return n.AsNonNullExpression().Expression() case KindTypeAssertionExpression: - return n.AsTypeAssertion().Expression + return n.AsTypeAssertion().Expression() case KindAsExpression: - return n.AsAsExpression().Expression + return n.AsAsExpression().Expression() case KindSatisfiesExpression: - return n.AsSatisfiesExpression().Expression + return n.AsSatisfiesExpression().Expression() case KindTypeOfExpression: - return n.AsTypeOfExpression().Expression + return n.AsTypeOfExpression().Expression() case KindSpreadAssignment: - return n.AsSpreadAssignment().Expression + return n.AsSpreadAssignment().Expression() case KindSpreadElement: - return n.AsSpreadElement().Expression + return n.AsSpreadElement().Expression() case KindTemplateSpan: - return n.AsTemplateSpan().Expression + return n.AsTemplateSpan().Expression() case KindDeleteExpression: - return n.AsDeleteExpression().Expression + return n.AsDeleteExpression().Expression() case KindVoidExpression: - return n.AsVoidExpression().Expression + return n.AsVoidExpression().Expression() case KindAwaitExpression: - return n.AsAwaitExpression().Expression + return n.AsAwaitExpression().Expression() case KindYieldExpression: - return n.AsYieldExpression().Expression + return n.AsYieldExpression().Expression() case KindPartiallyEmittedExpression: - return n.AsPartiallyEmittedExpression().Expression + return n.AsPartiallyEmittedExpression().Expression() case KindIfStatement: - return n.AsIfStatement().Expression + return n.AsIfStatement().Expression() case KindDoStatement: - return n.AsDoStatement().Expression + return n.AsDoStatement().Expression() case KindWhileStatement: - return n.AsWhileStatement().Expression + return n.AsWhileStatement().Expression() case KindWithStatement: - return n.AsWithStatement().Expression + return n.AsWithStatement().Expression() case KindForInStatement, KindForOfStatement: - return n.AsForInOrOfStatement().Expression + return n.AsForInOrOfStatement().Expression() case KindSwitchStatement: - return n.AsSwitchStatement().Expression + return n.AsSwitchStatement().Expression() case KindCaseClause: - return n.AsCaseOrDefaultClause().Expression + return n.AsCaseOrDefaultClause().Expression() case KindExpressionStatement: - return n.AsExpressionStatement().Expression + return n.AsExpressionStatement().Expression() case KindReturnStatement: - return n.AsReturnStatement().Expression + return n.AsReturnStatement().Expression() case KindThrowStatement: - return n.AsThrowStatement().Expression + return n.AsThrowStatement().Expression() case KindExternalModuleReference: - return n.AsExternalModuleReference().Expression + return n.AsExternalModuleReference().Expression() case KindExportAssignment: - return n.AsExportAssignment().Expression + return n.AsExportAssignment().Expression() case KindDecorator: - return n.AsDecorator().Expression + return n.AsDecorator().Expression() case KindJsxExpression: - return n.AsJsxExpression().Expression + return n.AsJsxExpression().Expression() case KindJsxSpreadAttribute: - return n.AsJsxSpreadAttribute().Expression + return n.AsJsxSpreadAttribute().Expression() } panic("Unhandled case in Node.Expression: " + n.Kind.String()) } @@ -400,75 +411,75 @@ func (m *MutableNode) SetExpression(expr *Node) { n := (*Node)(m) switch n.Kind { case KindPropertyAccessExpression: - n.AsPropertyAccessExpression().Expression = expr + n.AsPropertyAccessExpression().SetExpression(expr) case KindElementAccessExpression: - n.AsElementAccessExpression().Expression = expr + n.AsElementAccessExpression().SetExpression(expr) case KindParenthesizedExpression: - n.AsParenthesizedExpression().Expression = expr + n.AsParenthesizedExpression().SetExpression(expr) case KindCallExpression: - n.AsCallExpression().Expression = expr + n.AsCallExpression().SetExpression(expr) case KindNewExpression: - n.AsNewExpression().Expression = expr + n.AsNewExpression().SetExpression(expr) case KindExpressionWithTypeArguments: - n.AsExpressionWithTypeArguments().Expression = expr + n.AsExpressionWithTypeArguments().SetExpression(expr) case KindComputedPropertyName: - n.AsComputedPropertyName().Expression = expr + n.AsComputedPropertyName().SetExpression(expr) case KindNonNullExpression: - n.AsNonNullExpression().Expression = expr + n.AsNonNullExpression().SetExpression(expr) case KindTypeAssertionExpression: - n.AsTypeAssertion().Expression = expr + n.AsTypeAssertion().SetExpression(expr) case KindAsExpression: - n.AsAsExpression().Expression = expr + n.AsAsExpression().SetExpression(expr) case KindSatisfiesExpression: - n.AsSatisfiesExpression().Expression = expr + n.AsSatisfiesExpression().SetExpression(expr) case KindTypeOfExpression: - n.AsTypeOfExpression().Expression = expr + n.AsTypeOfExpression().SetExpression(expr) case KindSpreadAssignment: - n.AsSpreadAssignment().Expression = expr + n.AsSpreadAssignment().SetExpression(expr) case KindSpreadElement: - n.AsSpreadElement().Expression = expr + n.AsSpreadElement().SetExpression(expr) case KindTemplateSpan: - n.AsTemplateSpan().Expression = expr + n.AsTemplateSpan().SetExpression(expr) case KindDeleteExpression: - n.AsDeleteExpression().Expression = expr + n.AsDeleteExpression().SetExpression(expr) case KindVoidExpression: - n.AsVoidExpression().Expression = expr + n.AsVoidExpression().SetExpression(expr) case KindAwaitExpression: - n.AsAwaitExpression().Expression = expr + n.AsAwaitExpression().SetExpression(expr) case KindYieldExpression: - n.AsYieldExpression().Expression = expr + n.AsYieldExpression().SetExpression(expr) case KindPartiallyEmittedExpression: - n.AsPartiallyEmittedExpression().Expression = expr + n.AsPartiallyEmittedExpression().SetExpression(expr) case KindIfStatement: - n.AsIfStatement().Expression = expr + n.AsIfStatement().SetExpression(expr) case KindDoStatement: - n.AsDoStatement().Expression = expr + n.AsDoStatement().SetExpression(expr) case KindWhileStatement: - n.AsWhileStatement().Expression = expr + n.AsWhileStatement().SetExpression(expr) case KindWithStatement: - n.AsWithStatement().Expression = expr + n.AsWithStatement().SetExpression(expr) case KindForInStatement, KindForOfStatement: - n.AsForInOrOfStatement().Expression = expr + n.AsForInOrOfStatement().SetExpression(expr) case KindSwitchStatement: - n.AsSwitchStatement().Expression = expr + n.AsSwitchStatement().SetExpression(expr) case KindCaseClause: - n.AsCaseOrDefaultClause().Expression = expr + n.AsCaseOrDefaultClause().SetExpression(expr) case KindExpressionStatement: - n.AsExpressionStatement().Expression = expr + n.AsExpressionStatement().SetExpression(expr) case KindReturnStatement: - n.AsReturnStatement().Expression = expr + n.AsReturnStatement().SetExpression(expr) case KindThrowStatement: - n.AsThrowStatement().Expression = expr + n.AsThrowStatement().SetExpression(expr) case KindExternalModuleReference: - n.AsExternalModuleReference().Expression = expr + n.AsExternalModuleReference().SetExpression(expr) case KindExportAssignment: - n.AsExportAssignment().Expression = expr + n.AsExportAssignment().SetExpression(expr) case KindDecorator: - n.AsDecorator().Expression = expr + n.AsDecorator().SetExpression(expr) case KindJsxExpression: - n.AsJsxExpression().Expression = expr + n.AsJsxExpression().SetExpression(expr) case KindJsxSpreadAttribute: - n.AsJsxSpreadAttribute().Expression = expr + n.AsJsxSpreadAttribute().SetExpression(expr) default: panic("Unhandled case in mutableNode.SetExpression: " + n.Kind.String()) } @@ -477,9 +488,9 @@ func (m *MutableNode) SetExpression(expr *Node) { func (n *Node) ArgumentList() *NodeList { switch n.Kind { case KindCallExpression: - return n.AsCallExpression().Arguments + return n.AsCallExpression().Arguments() case KindNewExpression: - return n.AsNewExpression().Arguments + return n.AsNewExpression().Arguments() } panic("Unhandled case in Node.Arguments: " + n.Kind.String()) } @@ -495,23 +506,23 @@ func (n *Node) Arguments() []*Node { func (n *Node) TypeArgumentList() *NodeList { switch n.Kind { case KindCallExpression: - return n.AsCallExpression().TypeArguments + return n.AsCallExpression().TypeArguments() case KindNewExpression: - return n.AsNewExpression().TypeArguments + return n.AsNewExpression().TypeArguments() case KindTaggedTemplateExpression: - return n.AsTaggedTemplateExpression().TypeArguments + return n.AsTaggedTemplateExpression().TypeArguments() case KindTypeReference: - return n.AsTypeReferenceNode().TypeArguments + return n.AsTypeReferenceNode().TypeArguments() case KindExpressionWithTypeArguments: - return n.AsExpressionWithTypeArguments().TypeArguments + return n.AsExpressionWithTypeArguments().TypeArguments() case KindImportType: - return n.AsImportTypeNode().TypeArguments + return n.AsImportTypeNode().TypeArguments() case KindTypeQuery: - return n.AsTypeQueryNode().TypeArguments + return n.AsTypeQueryNode().TypeArguments() case KindJsxOpeningElement: - return n.AsJsxOpeningElement().TypeArguments + return n.AsJsxOpeningElement().TypeArguments() case KindJsxSelfClosingElement: - return n.AsJsxSelfClosingElement().TypeArguments + return n.AsJsxSelfClosingElement().TypeArguments() } panic("Unhandled case in Node.TypeArguments") } @@ -527,19 +538,19 @@ func (n *Node) TypeArguments() []*Node { func (n *Node) TypeParameterList() *NodeList { switch n.Kind { case KindClassDeclaration: - return n.AsClassDeclaration().TypeParameters + return n.AsClassDeclaration().TypeParameters() case KindClassExpression: - return n.AsClassExpression().TypeParameters + return n.AsClassExpression().TypeParameters() case KindInterfaceDeclaration: - return n.AsInterfaceDeclaration().TypeParameters + return n.AsInterfaceDeclaration().TypeParameters() case KindTypeAliasDeclaration, KindJSTypeAliasDeclaration: - return n.AsTypeAliasDeclaration().TypeParameters + return n.AsTypeAliasDeclaration().TypeParameters() case KindJSDocTemplateTag: - return n.AsJSDocTemplateTag().TypeParameters + return n.AsJSDocTemplateTag().TypeParameters() default: funcLike := n.FunctionLikeData() if funcLike != nil { - return funcLike.TypeParameters + return funcLike.TypeParameters() } } panic("Unhandled case in Node.TypeParameterList") @@ -556,17 +567,17 @@ func (n *Node) TypeParameters() []*Node { func (n *Node) MemberList() *NodeList { switch n.Kind { case KindClassDeclaration: - return n.AsClassDeclaration().Members + return n.AsClassDeclaration().Members() case KindClassExpression: - return n.AsClassExpression().Members + return n.AsClassExpression().Members() case KindInterfaceDeclaration: - return n.AsInterfaceDeclaration().Members + return n.AsInterfaceDeclaration().Members() case KindEnumDeclaration: - return n.AsEnumDeclaration().Members + return n.AsEnumDeclaration().Members() case KindTypeLiteral: - return n.AsTypeLiteralNode().Members + return n.AsTypeLiteralNode().Members() case KindMappedType: - return n.AsMappedTypeNode().Members + return n.AsMappedTypeNode().Members() } panic("Unhandled case in Node.MemberList: " + n.Kind.String()) } @@ -584,11 +595,11 @@ func (n *Node) StatementList() *NodeList { case KindSourceFile: return n.AsSourceFile().Statements case KindBlock: - return n.AsBlock().Statements + return n.AsBlock().Statements() case KindModuleBlock: - return n.AsModuleBlock().Statements + return n.AsModuleBlock().Statements() case KindCaseClause, KindDefaultClause: - return n.AsCaseOrDefaultClause().Statements + return n.AsCaseOrDefaultClause().Statements() } panic("Unhandled case in Node.StatementList: " + n.Kind.String()) } @@ -629,58 +640,58 @@ func (n *Node) ModifierNodes() []*Node { func (n *Node) Type() *Node { switch n.Kind { case KindVariableDeclaration: - return n.AsVariableDeclaration().Type + return n.AsVariableDeclaration().Type() case KindParameter: - return n.AsParameterDeclaration().Type + return n.AsParameterDeclaration().Type() case KindPropertySignature: - return n.AsPropertySignatureDeclaration().Type + return n.AsPropertySignatureDeclaration().Type() case KindPropertyDeclaration: - return n.AsPropertyDeclaration().Type + return n.AsPropertyDeclaration().Type() case KindPropertyAssignment: - return n.AsPropertyAssignment().Type + return n.AsPropertyAssignment().Type() case KindShorthandPropertyAssignment: - return n.AsShorthandPropertyAssignment().Type + return n.AsShorthandPropertyAssignment().Type() case KindTypePredicate: - return n.AsTypePredicateNode().Type + return n.AsTypePredicateNode().Type() case KindParenthesizedType: - return n.AsParenthesizedTypeNode().Type + return n.AsParenthesizedTypeNode().Type() case KindTypeOperator: - return n.AsTypeOperatorNode().Type + return n.AsTypeOperatorNode().Type() case KindMappedType: - return n.AsMappedTypeNode().Type + return n.AsMappedTypeNode().Type() case KindTypeAssertionExpression: - return n.AsTypeAssertion().Type + return n.AsTypeAssertion().Type() case KindAsExpression: - return n.AsAsExpression().Type + return n.AsAsExpression().Type() case KindSatisfiesExpression: - return n.AsSatisfiesExpression().Type + return n.AsSatisfiesExpression().Type() case KindTypeAliasDeclaration, KindJSTypeAliasDeclaration: - return n.AsTypeAliasDeclaration().Type + return n.AsTypeAliasDeclaration().Type() case KindNamedTupleMember: - return n.AsNamedTupleMember().Type + return n.AsNamedTupleMember().Type() case KindOptionalType: - return n.AsOptionalTypeNode().Type + return n.AsOptionalTypeNode().Type() case KindRestType: - return n.AsRestTypeNode().Type + return n.AsRestTypeNode().Type() case KindTemplateLiteralTypeSpan: - return n.AsTemplateLiteralTypeSpan().Type + return n.AsTemplateLiteralTypeSpan().Type() case KindJSDocTypeExpression: - return n.AsJSDocTypeExpression().Type + return n.AsJSDocTypeExpression().Type() case KindJSDocParameterTag, KindJSDocPropertyTag: - return n.AsJSDocParameterOrPropertyTag().TypeExpression + return n.AsJSDocParameterOrPropertyTag().TypeExpression() case KindJSDocNullableType: - return n.AsJSDocNullableType().Type + return n.AsJSDocNullableType().Type() case KindJSDocNonNullableType: - return n.AsJSDocNonNullableType().Type + return n.AsJSDocNonNullableType().Type() case KindJSDocOptionalType: - return n.AsJSDocOptionalType().Type + return n.AsJSDocOptionalType().Type() case KindExportAssignment: - return n.AsExportAssignment().Type + return n.AsExportAssignment().Type() case KindBinaryExpression: - return n.AsBinaryExpression().Type + return n.AsBinaryExpression().Type() default: if funcLike := n.FunctionLikeData(); funcLike != nil { - return funcLike.Type + return funcLike.Type() } } return nil @@ -690,58 +701,58 @@ func (m *MutableNode) SetType(t *Node) { n := (*Node)(m) switch m.Kind { case KindVariableDeclaration: - n.AsVariableDeclaration().Type = t + n.AsVariableDeclaration().SetType(t) case KindParameter: - n.AsParameterDeclaration().Type = t + n.AsParameterDeclaration().SetType(t) case KindPropertySignature: - n.AsPropertySignatureDeclaration().Type = t + n.AsPropertySignatureDeclaration().SetType(t) case KindPropertyDeclaration: - n.AsPropertyDeclaration().Type = t + n.AsPropertyDeclaration().SetType(t) case KindPropertyAssignment: - n.AsPropertyAssignment().Type = t + n.AsPropertyAssignment().SetType(t) case KindShorthandPropertyAssignment: - n.AsShorthandPropertyAssignment().Type = t + n.AsShorthandPropertyAssignment().SetType(t) case KindTypePredicate: - n.AsTypePredicateNode().Type = t + n.AsTypePredicateNode().SetType(t) case KindParenthesizedType: - n.AsParenthesizedTypeNode().Type = t + n.AsParenthesizedTypeNode().SetType(t) case KindTypeOperator: - n.AsTypeOperatorNode().Type = t + n.AsTypeOperatorNode().SetType(t) case KindMappedType: - n.AsMappedTypeNode().Type = t + n.AsMappedTypeNode().SetType(t) case KindTypeAssertionExpression: - n.AsTypeAssertion().Type = t + n.AsTypeAssertion().SetType(t) case KindAsExpression: - n.AsAsExpression().Type = t + n.AsAsExpression().SetType(t) case KindSatisfiesExpression: - n.AsSatisfiesExpression().Type = t + n.AsSatisfiesExpression().SetType(t) case KindTypeAliasDeclaration, KindJSTypeAliasDeclaration: - n.AsTypeAliasDeclaration().Type = t + n.AsTypeAliasDeclaration().SetType(t) case KindNamedTupleMember: - n.AsNamedTupleMember().Type = t + n.AsNamedTupleMember().SetType(t) case KindOptionalType: - n.AsOptionalTypeNode().Type = t + n.AsOptionalTypeNode().SetType(t) case KindRestType: - n.AsRestTypeNode().Type = t + n.AsRestTypeNode().SetType(t) case KindTemplateLiteralTypeSpan: - n.AsTemplateLiteralTypeSpan().Type = t + n.AsTemplateLiteralTypeSpan().SetType(t) case KindJSDocTypeExpression: - n.AsJSDocTypeExpression().Type = t + n.AsJSDocTypeExpression().SetType(t) case KindJSDocParameterTag, KindJSDocPropertyTag: - n.AsJSDocParameterOrPropertyTag().TypeExpression = t + n.AsJSDocParameterOrPropertyTag().SetTypeExpression(t) case KindJSDocNullableType: - n.AsJSDocNullableType().Type = t + n.AsJSDocNullableType().SetType(t) case KindJSDocNonNullableType: - n.AsJSDocNonNullableType().Type = t + n.AsJSDocNonNullableType().SetType(t) case KindJSDocOptionalType: - n.AsJSDocOptionalType().Type = t + n.AsJSDocOptionalType().SetType(t) case KindExportAssignment: - n.AsExportAssignment().Type = t + n.AsExportAssignment().SetType(t) case KindBinaryExpression: - n.AsBinaryExpression().Type = t + n.AsBinaryExpression().SetType(t) default: if funcLike := n.FunctionLikeData(); funcLike != nil { - funcLike.Type = t + funcLike.SetType(t) } else { panic("Unhandled case in mutableNode.SetType: " + n.Kind.String()) } @@ -751,25 +762,25 @@ func (m *MutableNode) SetType(t *Node) { func (n *Node) Initializer() *Node { switch n.Kind { case KindVariableDeclaration: - return n.AsVariableDeclaration().Initializer + return n.AsVariableDeclaration().Initializer() case KindParameter: - return n.AsParameterDeclaration().Initializer + return n.AsParameterDeclaration().Initializer() case KindBindingElement: - return n.AsBindingElement().Initializer + return n.AsBindingElement().Initializer() case KindPropertyDeclaration: - return n.AsPropertyDeclaration().Initializer + return n.AsPropertyDeclaration().Initializer() case KindPropertySignature: - return n.AsPropertySignatureDeclaration().Initializer + return n.AsPropertySignatureDeclaration().Initializer() case KindPropertyAssignment: - return n.AsPropertyAssignment().Initializer + return n.AsPropertyAssignment().Initializer() case KindEnumMember: - return n.AsEnumMember().Initializer + return n.AsEnumMember().Initializer() case KindForStatement: - return n.AsForStatement().Initializer + return n.AsForStatement().Initializer() case KindForInStatement, KindForOfStatement: - return n.AsForInOrOfStatement().Initializer + return n.AsForInOrOfStatement().Initializer() case KindJsxAttribute: - return n.AsJsxAttribute().Initializer + return n.AsJsxAttribute().Initializer() } panic("Unhandled case in Node.Initializer") } @@ -778,25 +789,25 @@ func (m *MutableNode) SetInitializer(initializer *Node) { n := (*Node)(m) switch n.Kind { case KindVariableDeclaration: - n.AsVariableDeclaration().Initializer = initializer + n.AsVariableDeclaration().SetInitializer(initializer) case KindParameter: - n.AsParameterDeclaration().Initializer = initializer + n.AsParameterDeclaration().SetInitializer(initializer) case KindBindingElement: - n.AsBindingElement().Initializer = initializer + n.AsBindingElement().SetInitializer(initializer) case KindPropertyDeclaration: - n.AsPropertyDeclaration().Initializer = initializer + n.AsPropertyDeclaration().SetInitializer(initializer) case KindPropertySignature: - n.AsPropertySignatureDeclaration().Initializer = initializer + n.AsPropertySignatureDeclaration().SetInitializer(initializer) case KindPropertyAssignment: - n.AsPropertyAssignment().Initializer = initializer + n.AsPropertyAssignment().SetInitializer(initializer) case KindEnumMember: - n.AsEnumMember().Initializer = initializer + n.AsEnumMember().SetInitializer(initializer) case KindForStatement: - n.AsForStatement().Initializer = initializer + n.AsForStatement().SetInitializer(initializer) case KindForInStatement, KindForOfStatement: - n.AsForInOrOfStatement().Initializer = initializer + n.AsForInOrOfStatement().SetInitializer(initializer) case KindJsxAttribute: - n.AsJsxAttribute().Initializer = initializer + n.AsJsxAttribute().SetInitializer(initializer) default: panic("Unhandled case in mutableNode.SetInitializer") } @@ -805,53 +816,53 @@ func (m *MutableNode) SetInitializer(initializer *Node) { func (n *Node) TagName() *Node { switch n.Kind { case KindJsxOpeningElement: - return n.AsJsxOpeningElement().TagName + return n.AsJsxOpeningElement().TagName() case KindJsxClosingElement: - return n.AsJsxClosingElement().TagName + return n.AsJsxClosingElement().TagName() case KindJsxSelfClosingElement: - return n.AsJsxSelfClosingElement().TagName + return n.AsJsxSelfClosingElement().TagName() case KindJSDocUnknownTag: - return n.AsJSDocUnknownTag().TagName + return n.AsJSDocUnknownTag().TagName() case KindJSDocAugmentsTag: - return n.AsJSDocAugmentsTag().TagName + return n.AsJSDocAugmentsTag().TagName() case KindJSDocImplementsTag: - return n.AsJSDocImplementsTag().TagName + return n.AsJSDocImplementsTag().TagName() case KindJSDocDeprecatedTag: - return n.AsJSDocDeprecatedTag().TagName + return n.AsJSDocDeprecatedTag().TagName() case KindJSDocPublicTag: - return n.AsJSDocPublicTag().TagName + return n.AsJSDocPublicTag().TagName() case KindJSDocPrivateTag: - return n.AsJSDocPrivateTag().TagName + return n.AsJSDocPrivateTag().TagName() case KindJSDocProtectedTag: - return n.AsJSDocProtectedTag().TagName + return n.AsJSDocProtectedTag().TagName() case KindJSDocReadonlyTag: - return n.AsJSDocReadonlyTag().TagName + return n.AsJSDocReadonlyTag().TagName() case KindJSDocOverrideTag: - return n.AsJSDocOverrideTag().TagName + return n.AsJSDocOverrideTag().TagName() case KindJSDocCallbackTag: - return n.AsJSDocCallbackTag().TagName + return n.AsJSDocCallbackTag().TagName() case KindJSDocOverloadTag: - return n.AsJSDocOverloadTag().TagName + return n.AsJSDocOverloadTag().TagName() case KindJSDocParameterTag, KindJSDocPropertyTag: - return n.AsJSDocParameterOrPropertyTag().TagName + return n.AsJSDocParameterOrPropertyTag().TagName() case KindJSDocReturnTag: - return n.AsJSDocReturnTag().TagName + return n.AsJSDocReturnTag().TagName() case KindJSDocThisTag: - return n.AsJSDocThisTag().TagName + return n.AsJSDocThisTag().TagName() case KindJSDocTypeTag: - return n.AsJSDocTypeTag().TagName + return n.AsJSDocTypeTag().TagName() case KindJSDocTemplateTag: - return n.AsJSDocTemplateTag().TagName + return n.AsJSDocTemplateTag().TagName() case KindJSDocTypedefTag: - return n.AsJSDocTypedefTag().TagName + return n.AsJSDocTypedefTag().TagName() case KindJSDocSeeTag: - return n.AsJSDocSeeTag().TagName + return n.AsJSDocSeeTag().TagName() case KindJSDocSatisfiesTag: - return n.AsJSDocSatisfiesTag().TagName + return n.AsJSDocSatisfiesTag().TagName() case KindJSDocThrowsTag: - return n.AsJSDocThrowsTag().TagName + return n.AsJSDocThrowsTag().TagName() case KindJSDocImportTag: - return n.AsJSDocImportTag().TagName + return n.AsJSDocImportTag().TagName() } panic("Unhandled case in Node.TagName: " + n.Kind.String()) } @@ -859,11 +870,11 @@ func (n *Node) TagName() *Node { func (n *Node) PropertyName() *Node { switch n.Kind { case KindImportSpecifier: - return n.AsImportSpecifier().PropertyName + return n.AsImportSpecifier().PropertyName() case KindExportSpecifier: - return n.AsExportSpecifier().PropertyName + return n.AsExportSpecifier().PropertyName() case KindBindingElement: - return n.AsBindingElement().PropertyName + return n.AsBindingElement().PropertyName() } return nil } @@ -896,49 +907,49 @@ func (n *Node) IsTypeOnly() bool { func (n *Node) CommentList() *NodeList { switch n.Kind { case KindJSDoc: - return n.AsJSDoc().Comment + return n.AsJSDoc().Comment() case KindJSDocUnknownTag: - return n.AsJSDocUnknownTag().Comment + return n.AsJSDocUnknownTag().Comment() case KindJSDocAugmentsTag: - return n.AsJSDocAugmentsTag().Comment + return n.AsJSDocAugmentsTag().Comment() case KindJSDocImplementsTag: - return n.AsJSDocImplementsTag().Comment + return n.AsJSDocImplementsTag().Comment() case KindJSDocDeprecatedTag: - return n.AsJSDocDeprecatedTag().Comment + return n.AsJSDocDeprecatedTag().Comment() case KindJSDocPublicTag: - return n.AsJSDocPublicTag().Comment + return n.AsJSDocPublicTag().Comment() case KindJSDocPrivateTag: - return n.AsJSDocPrivateTag().Comment + return n.AsJSDocPrivateTag().Comment() case KindJSDocProtectedTag: - return n.AsJSDocProtectedTag().Comment + return n.AsJSDocProtectedTag().Comment() case KindJSDocReadonlyTag: - return n.AsJSDocReadonlyTag().Comment + return n.AsJSDocReadonlyTag().Comment() case KindJSDocOverrideTag: - return n.AsJSDocOverrideTag().Comment + return n.AsJSDocOverrideTag().Comment() case KindJSDocCallbackTag: - return n.AsJSDocCallbackTag().Comment + return n.AsJSDocCallbackTag().Comment() case KindJSDocOverloadTag: - return n.AsJSDocOverloadTag().Comment + return n.AsJSDocOverloadTag().Comment() case KindJSDocParameterTag, KindJSDocPropertyTag: - return n.AsJSDocParameterOrPropertyTag().Comment + return n.AsJSDocParameterOrPropertyTag().Comment() case KindJSDocReturnTag: - return n.AsJSDocReturnTag().Comment + return n.AsJSDocReturnTag().Comment() case KindJSDocThisTag: - return n.AsJSDocThisTag().Comment + return n.AsJSDocThisTag().Comment() case KindJSDocTypeTag: - return n.AsJSDocTypeTag().Comment + return n.AsJSDocTypeTag().Comment() case KindJSDocTemplateTag: - return n.AsJSDocTemplateTag().Comment + return n.AsJSDocTemplateTag().Comment() case KindJSDocTypedefTag: - return n.AsJSDocTypedefTag().Comment + return n.AsJSDocTypedefTag().Comment() case KindJSDocSeeTag: - return n.AsJSDocSeeTag().Comment + return n.AsJSDocSeeTag().Comment() case KindJSDocSatisfiesTag: - return n.AsJSDocSatisfiesTag().Comment + return n.AsJSDocSatisfiesTag().Comment() case KindJSDocThrowsTag: - return n.AsJSDocThrowsTag().Comment + return n.AsJSDocThrowsTag().Comment() case KindJSDocImportTag: - return n.AsJSDocImportTag().Comment + return n.AsJSDocImportTag().Comment() } panic("Unhandled case in Node.CommentList: " + n.Kind.String()) } @@ -954,11 +965,11 @@ func (n *Node) Comments() []*Node { func (n *Node) Label() *Node { switch n.Kind { case KindLabeledStatement: - return n.AsLabeledStatement().Label + return n.AsLabeledStatement().Label() case KindBreakStatement: - return n.AsBreakStatement().Label + return n.AsBreakStatement().Label() case KindContinueStatement: - return n.AsContinueStatement().Label + return n.AsContinueStatement().Label() } panic("Unhandled case in Node.Label: " + n.Kind.String()) } @@ -966,11 +977,11 @@ func (n *Node) Label() *Node { func (n *Node) Attributes() *Node { switch n.Kind { case KindJsxOpeningElement: - return n.AsJsxOpeningElement().Attributes + return n.AsJsxOpeningElement().Attributes() case KindJsxSelfClosingElement: - return n.AsJsxSelfClosingElement().Attributes + return n.AsJsxSelfClosingElement().Attributes() case KindModuleDeclaration: - return n.AsModuleDeclaration().Attributes + return n.AsModuleDeclaration().Attributes() } panic("Unhandled case in Node.Attributes: " + n.Kind.String()) } @@ -978,9 +989,9 @@ func (n *Node) Attributes() *Node { func (n *Node) Children() *NodeList { switch n.Kind { case KindJsxElement: - return n.AsJsxElement().Children + return n.AsJsxElement().Children() case KindJsxFragment: - return n.AsJsxFragment().Children + return n.AsJsxFragment().Children() } panic("Unhandled case in Node.Children: " + n.Kind.String()) } @@ -988,11 +999,11 @@ func (n *Node) Children() *NodeList { func (n *Node) ModuleSpecifier() *Expression { switch n.Kind { case KindImportDeclaration, KindJSImportDeclaration: - return n.AsImportDeclaration().ModuleSpecifier + return n.AsImportDeclaration().ModuleSpecifier() case KindExportDeclaration: - return n.AsExportDeclaration().ModuleSpecifier + return n.AsExportDeclaration().ModuleSpecifier() case KindJSDocImportTag: - return n.AsJSDocImportTag().ModuleSpecifier + return n.AsJSDocImportTag().ModuleSpecifier() } panic("Unhandled case in Node.ModuleSpecifier: " + n.Kind.String()) } @@ -1000,9 +1011,9 @@ func (n *Node) ModuleSpecifier() *Expression { func (n *Node) ImportClause() *Node { switch n.Kind { case KindImportDeclaration, KindJSImportDeclaration: - return n.AsImportDeclaration().ImportClause + return n.AsImportDeclaration().ImportClause() case KindJSDocImportTag: - return n.AsJSDocImportTag().ImportClause + return n.AsJSDocImportTag().ImportClause() } panic("Unhandled case in Node.ImportClause: " + n.Kind.String()) } @@ -1010,17 +1021,17 @@ func (n *Node) ImportClause() *Node { func (n *Node) Statement() *Statement { switch n.Kind { case KindDoStatement: - return n.AsDoStatement().Statement + return n.AsDoStatement().Statement() case KindWhileStatement: - return n.AsWhileStatement().Statement + return n.AsWhileStatement().Statement() case KindForStatement: - return n.AsForStatement().Statement + return n.AsForStatement().Statement() case KindForInStatement, KindForOfStatement: - return n.AsForInOrOfStatement().Statement + return n.AsForInOrOfStatement().Statement() case KindWithStatement: - return n.AsWithStatement().Statement + return n.AsWithStatement().Statement() case KindLabeledStatement: - return n.AsLabeledStatement().Statement + return n.AsLabeledStatement().Statement() } panic("Unhandled case in Node.Statement: " + n.Kind.String()) } @@ -1028,9 +1039,9 @@ func (n *Node) Statement() *Statement { func (n *Node) PropertyList() *NodeList { switch n.Kind { case KindObjectLiteralExpression: - return n.AsObjectLiteralExpression().Properties + return n.AsObjectLiteralExpression().Properties() case KindJsxAttributes: - return n.AsJsxAttributes().Properties + return n.AsJsxAttributes().Properties() } panic("Unhandled case in Node.PropertyList: " + n.Kind.String()) } @@ -1046,15 +1057,15 @@ func (n *Node) Properties() []*Node { func (n *Node) ElementList() *NodeList { switch n.Kind { case KindNamedImports: - return n.AsNamedImports().Elements + return n.AsNamedImports().Elements() case KindNamedExports: - return n.AsNamedExports().Elements + return n.AsNamedExports().Elements() case KindObjectBindingPattern, KindArrayBindingPattern: - return n.AsBindingPattern().Elements + return n.AsBindingPattern().Elements() case KindArrayLiteralExpression: - return n.AsArrayLiteralExpression().Elements + return n.AsArrayLiteralExpression().Elements() case KindTupleType: - return n.AsTupleTypeNode().Elements + return n.AsTupleTypeNode().Elements() } panic("Unhandled case in Node.ElementList: " + n.Kind.String()) } @@ -1070,23 +1081,23 @@ func (n *Node) Elements() []*Node { func (n *Node) PostfixToken() *Node { switch n.Kind { case KindMethodDeclaration: - return n.AsMethodDeclaration().PostfixToken + return n.AsMethodDeclaration().PostfixToken() case KindShorthandPropertyAssignment: - return n.AsShorthandPropertyAssignment().PostfixToken + return n.AsShorthandPropertyAssignment().PostfixToken() case KindMethodSignature: - return n.AsMethodSignatureDeclaration().PostfixToken + return n.AsMethodSignatureDeclaration().PostfixToken() case KindPropertySignature: - return n.AsPropertySignatureDeclaration().PostfixToken + return n.AsPropertySignatureDeclaration().PostfixToken() case KindPropertyAssignment: - return n.AsPropertyAssignment().PostfixToken + return n.AsPropertyAssignment().PostfixToken() case KindPropertyDeclaration: - return n.AsPropertyDeclaration().PostfixToken + return n.AsPropertyDeclaration().PostfixToken() case KindEnumMember: - return n.AsEnumMember().PostfixToken + return n.AsEnumMember().PostfixToken() case KindGetAccessor: - return n.AsGetAccessorDeclaration().PostfixToken + return n.AsGetAccessorDeclaration().PostfixToken() case KindSetAccessor: - return n.AsSetAccessorDeclaration().PostfixToken + return n.AsSetAccessorDeclaration().PostfixToken() } return nil } @@ -1094,13 +1105,13 @@ func (n *Node) PostfixToken() *Node { func (n *Node) QuestionToken() *TokenNode { switch n.Kind { case KindParameter: - return n.AsParameterDeclaration().QuestionToken + return n.AsParameterDeclaration().QuestionToken() case KindConditionalExpression: - return n.AsConditionalExpression().QuestionToken + return n.AsConditionalExpression().QuestionToken() case KindMappedType: - return n.AsMappedTypeNode().QuestionToken + return n.AsMappedTypeNode().QuestionToken() case KindNamedTupleMember: - return n.AsNamedTupleMember().QuestionToken + return n.AsNamedTupleMember().QuestionToken() } postfix := n.PostfixToken() if postfix != nil && postfix.Kind == KindQuestionToken { @@ -1112,13 +1123,13 @@ func (n *Node) QuestionToken() *TokenNode { func (n *Node) QuestionDotToken() *Node { switch n.Kind { case KindElementAccessExpression: - return n.AsElementAccessExpression().QuestionDotToken + return n.AsElementAccessExpression().QuestionDotToken() case KindPropertyAccessExpression: - return n.AsPropertyAccessExpression().QuestionDotToken + return n.AsPropertyAccessExpression().QuestionDotToken() case KindCallExpression: - return n.AsCallExpression().QuestionDotToken + return n.AsCallExpression().QuestionDotToken() case KindTaggedTemplateExpression: - return n.AsTaggedTemplateExpression().QuestionDotToken + return n.AsTaggedTemplateExpression().QuestionDotToken() } panic("Unhandled case in Node.QuestionDotToken: " + n.Kind.String()) } @@ -1126,19 +1137,19 @@ func (n *Node) QuestionDotToken() *Node { func (n *Node) TypeExpression() *Node { switch n.Kind { case KindJSDocParameterTag, KindJSDocPropertyTag: - return n.AsJSDocParameterOrPropertyTag().TypeExpression + return n.AsJSDocParameterOrPropertyTag().TypeExpression() case KindJSDocReturnTag: - return n.AsJSDocReturnTag().TypeExpression + return n.AsJSDocReturnTag().TypeExpression() case KindJSDocTypeTag: - return n.AsJSDocTypeTag().TypeExpression + return n.AsJSDocTypeTag().TypeExpression() case KindJSDocTypedefTag: - return n.AsJSDocTypedefTag().TypeExpression + return n.AsJSDocTypedefTag().TypeExpression() case KindJSDocCallbackTag: - return n.AsJSDocCallbackTag().TypeExpression + return n.AsJSDocCallbackTag().TypeExpression() case KindJSDocSatisfiesTag: - return n.AsJSDocSatisfiesTag().TypeExpression + return n.AsJSDocSatisfiesTag().TypeExpression() case KindJSDocThrowsTag: - return n.AsJSDocThrowsTag().TypeExpression + return n.AsJSDocThrowsTag().TypeExpression() } panic("Unhandled case in Node.TypeExpression: " + n.Kind.String()) } @@ -1146,9 +1157,9 @@ func (n *Node) TypeExpression() *Node { func (n *Node) ClassName() *Node { switch n.Kind { case KindJSDocAugmentsTag: - return n.AsJSDocAugmentsTag().ClassName + return n.AsJSDocAugmentsTag().ClassName() case KindJSDocImplementsTag: - return n.AsJSDocImplementsTag().ClassName + return n.AsJSDocImplementsTag().ClassName() } panic("Unhandled case in Node.ClassName: " + n.Kind.String()) } @@ -1160,7 +1171,7 @@ func (n *Node) Contains(descendant *Node) bool { if descendant == n { return true } - parent := descendant.Parent + parent := descendant.Parent() if parent == nil && !IsSourceFile(descendant) { panic("descendant is not parented") } @@ -1279,14 +1290,14 @@ func IsWriteAccessForReference(node *Node) bool { } func GetDeclarationFromName(name *Node) *Declaration { - if name == nil || name.Parent == nil { + if name == nil || name.Parent() == nil { return nil } - parent := name.Parent + parent := name.Parent() switch name.Kind { case KindStringLiteral, KindNoSubstitutionTemplateLiteral, KindNumericLiteral: if IsComputedPropertyName(parent) { - return parent.Parent + return parent.Parent() } fallthrough case KindIdentifier: @@ -1297,17 +1308,17 @@ func GetDeclarationFromName(name *Node) *Declaration { return nil } if IsQualifiedName(parent) { - tag := parent.Parent + tag := parent.Parent() if IsJSDocParameterTag(tag) && tag.Name() == parent { return tag } return nil } - binExp := parent.Parent + binExp := parent.Parent() if IsBinaryExpression(binExp) && GetAssignmentDeclarationKind(binExp) != JSDeclarationKindNone { // (binExp.left as BindableStaticNameExpression).symbol || binExp.symbol leftHasSymbol := false - if binExp.AsBinaryExpression().Left != nil && binExp.AsBinaryExpression().Left.Symbol() != nil { + if binExp.AsBinaryExpression().Left() != nil && binExp.AsBinaryExpression().Left().Symbol() != nil { leftHasSymbol = true } if leftHasSymbol || binExp.Symbol() != nil { @@ -1362,24 +1373,24 @@ func declarationIsWriteAccess(decl *Node) bool { case KindPropertyAssignment: // In `({ x: y } = 0);`, `x` is not a write access. - return !IsArrayLiteralOrObjectLiteralDestructuringPattern(decl.Parent) + return !IsArrayLiteralOrObjectLiteralDestructuringPattern(decl.Parent()) case KindFunctionDeclaration, KindFunctionExpression, KindConstructor, KindMethodDeclaration, KindGetAccessor, KindSetAccessor: // functions considered write if they provide a value (have a body) switch decl.Kind { case KindFunctionDeclaration: - return decl.AsFunctionDeclaration().Body != nil + return decl.AsFunctionDeclaration().Body() != nil case KindFunctionExpression: - return decl.AsFunctionExpression().Body != nil + return decl.AsFunctionExpression().Body() != nil case KindConstructor: // constructor node stores body on the parent? treat same as others - return decl.AsConstructorDeclaration().Body != nil + return decl.AsConstructorDeclaration().Body() != nil case KindMethodDeclaration: - return decl.AsMethodDeclaration().Body != nil + return decl.AsMethodDeclaration().Body() != nil case KindGetAccessor: - return decl.AsGetAccessorDeclaration().Body != nil + return decl.AsGetAccessorDeclaration().Body() != nil case KindSetAccessor: - return decl.AsSetAccessorDeclaration().Body != nil + return decl.AsSetAccessorDeclaration().Body() != nil } return false @@ -1388,11 +1399,11 @@ func declarationIsWriteAccess(decl *Node) bool { var hasInit bool switch decl.Kind { case KindVariableDeclaration: - hasInit = decl.AsVariableDeclaration().Initializer != nil + hasInit = decl.AsVariableDeclaration().Initializer() != nil case KindPropertyDeclaration: - hasInit = decl.AsPropertyDeclaration().Initializer != nil + hasInit = decl.AsPropertyDeclaration().Initializer() != nil } - return hasInit || IsCatchClause(decl.Parent) + return hasInit || IsCatchClause(decl.Parent()) case KindMethodSignature, KindPropertySignature, KindJSDocPropertyTag, KindJSDocParameterTag: return false @@ -1407,10 +1418,10 @@ func IsArrayLiteralOrObjectLiteralDestructuringPattern(node *Node) bool { if !(IsArrayLiteralExpression(node) || IsObjectLiteralExpression(node)) { return false } - parent := node.Parent + parent := node.Parent() // [a,b,c] from: // [a, b, c] = someExpression; - if IsBinaryExpression(parent) && parent.AsBinaryExpression().Left == node && parent.AsBinaryExpression().OperatorToken.Kind == KindEqualsToken { + if IsBinaryExpression(parent) && parent.AsBinaryExpression().Left() == node && parent.AsBinaryExpression().OperatorToken().Kind == KindEqualsToken { return true } // [a, b, c] from: @@ -1420,7 +1431,7 @@ func IsArrayLiteralOrObjectLiteralDestructuringPattern(node *Node) bool { } // {x, a: {a, b, c} } = someExpression if IsPropertyAssignment(parent) { - return IsArrayLiteralOrObjectLiteralDestructuringPattern(parent.Parent) + return IsArrayLiteralOrObjectLiteralDestructuringPattern(parent.Parent()) } // [a, b, c] of // [x, [a, b, c] ] = someExpression @@ -1428,7 +1439,7 @@ func IsArrayLiteralOrObjectLiteralDestructuringPattern(node *Node) bool { } func accessKind(node *Node) AccessKind { - parent := node.Parent + parent := node.Parent() if parent == nil { return AccessKindRead } @@ -1448,8 +1459,8 @@ func accessKind(node *Node) AccessKind { } return AccessKindRead case KindBinaryExpression: - if parent.AsBinaryExpression().Left == node { - operator := parent.AsBinaryExpression().OperatorToken + if parent.AsBinaryExpression().Left() == node { + operator := parent.AsBinaryExpression().OperatorToken() if IsAssignmentOperator(operator.Kind) { if operator.Kind == KindEqualsToken { return AccessKindWrite @@ -1464,7 +1475,7 @@ func accessKind(node *Node) AccessKind { } return accessKind(parent) case KindPropertyAssignment: - parentAccess := accessKind(parent.Parent) + parentAccess := accessKind(parent.Parent()) // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. if node == parent.AsPropertyAssignment().Name() { return reverseAccessKind(parentAccess) @@ -1472,14 +1483,14 @@ func accessKind(node *Node) AccessKind { return parentAccess case KindShorthandPropertyAssignment: // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. - if node == parent.AsShorthandPropertyAssignment().ObjectAssignmentInitializer { + if node == parent.AsShorthandPropertyAssignment().ObjectAssignmentInitializer() { return AccessKindRead } - return accessKind(parent.Parent) + return accessKind(parent.Parent()) case KindArrayLiteralExpression: return accessKind(parent) case KindForInStatement, KindForOfStatement: - if node == parent.AsForInOrOfStatement().Initializer { + if node == parent.AsForInOrOfStatement().Initializer() { return AccessKindWrite } return AccessKindRead @@ -1522,8 +1533,8 @@ func (node *ExportableBase) ExportableData() *ExportableBase { return node } // ModifiersBase -func (node *ModifiersBase) Modifiers() *ModifierList { return node.modifiers } -func (node *ModifiersBase) setModifiers(modifiers *ModifierList) { node.modifiers = modifiers } +func (node *ModifiersBase) Modifiers() *ModifierList { return node.modifiers.get() } +func (node *ModifiersBase) setModifiers(modifiers *ModifierList) { node.modifiers.set(modifiers) } // LocalsContainerBase @@ -1676,27 +1687,27 @@ func (f *NodeFactory) NewModifier(kind Kind) *Node { } func (node *Decorator) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | + return propagateSubtreeFacts(node.Expression()) | SubtreeContainsTypeScript | SubtreeContainsDecorators } func (node *ForInOrOfStatement) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Initializer) | - propagateSubtreeFacts(node.Expression) | - propagateSubtreeFacts(node.Statement) | - core.IfElse(node.AwaitModifier != nil, SubtreeContainsForAwaitOrAsyncGenerator, SubtreeFactsNone) + return propagateSubtreeFacts(node.Initializer()) | + propagateSubtreeFacts(node.Expression()) | + propagateSubtreeFacts(node.Statement()) | + core.IfElse(node.AwaitModifier() != nil, SubtreeContainsForAwaitOrAsyncGenerator, SubtreeFactsNone) } func (node *ReturnStatement) computeSubtreeFacts() SubtreeFacts { // return in an ES2018 async generator must be awaited - return propagateSubtreeFacts(node.Expression) | SubtreeContainsForAwaitOrAsyncGenerator + return propagateSubtreeFacts(node.Expression()) | SubtreeContainsForAwaitOrAsyncGenerator } func (node *CatchClause) computeSubtreeFacts() SubtreeFacts { - res := propagateSubtreeFacts(node.VariableDeclaration) | - propagateSubtreeFacts(node.Block) - if node.VariableDeclaration == nil { + res := propagateSubtreeFacts(node.VariableDeclaration()) | + propagateSubtreeFacts(node.Block()) + if node.VariableDeclaration() == nil { res |= SubtreeContainsMissingCatchClauseVariable } return res @@ -1707,23 +1718,23 @@ func (node *CatchClause) propagateSubtreeFacts() SubtreeFacts { } func (node *VariableStatement) computeSubtreeFacts() SubtreeFacts { - if node.modifiers != nil && node.modifiers.ModifierFlags&ModifierFlagsAmbient != 0 { + if node.modifiers.get() != nil && node.modifiers.get().ModifierFlags&ModifierFlagsAmbient != 0 { return SubtreeContainsTypeScript } else { - return propagateModifierListSubtreeFacts(node.modifiers) | - propagateSubtreeFacts(node.DeclarationList) + return propagateModifierListSubtreeFacts(node.modifiers.get()) | + propagateSubtreeFacts(node.DeclarationList()) } } func (node *VariableDeclaration) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.name) | - propagateEraseableSyntaxSubtreeFacts(node.ExclamationToken) | - propagateEraseableSyntaxSubtreeFacts(node.Type) | - propagateSubtreeFacts(node.Initializer) + return propagateSubtreeFacts(node.name.get()) | + propagateEraseableSyntaxSubtreeFacts(node.ExclamationToken()) | + propagateEraseableSyntaxSubtreeFacts(node.Type()) | + propagateSubtreeFacts(node.Initializer()) } func (node *VariableDeclarationList) computeSubtreeFacts() SubtreeFacts { - return propagateNodeListSubtreeFacts(node.Declarations, propagateSubtreeFacts) | + return propagateNodeListSubtreeFacts(node.Declarations(), propagateSubtreeFacts) | core.IfElse(node.Flags&NodeFlagsUsing != 0, SubtreeContainsUsing, SubtreeFactsNone) } @@ -1734,9 +1745,9 @@ func (node *VariableDeclarationList) propagateSubtreeFacts() SubtreeFacts { func (node *BindingPattern) computeSubtreeFacts() SubtreeFacts { switch node.Kind { case KindObjectBindingPattern: - return propagateNodeListSubtreeFacts(node.Elements, propagateObjectBindingElementSubtreeFacts) + return propagateNodeListSubtreeFacts(node.Elements(), propagateObjectBindingElementSubtreeFacts) case KindArrayBindingPattern: - return propagateNodeListSubtreeFacts(node.Elements, propagateBindingElementSubtreeFacts) + return propagateNodeListSubtreeFacts(node.Elements(), propagateBindingElementSubtreeFacts) default: return SubtreeFactsNone } @@ -1747,14 +1758,14 @@ func (node *BindingPattern) propagateSubtreeFacts() SubtreeFacts { } func (node *ParameterDeclaration) computeSubtreeFacts() SubtreeFacts { - if node.name != nil && IsThisIdentifier(node.name) { + if node.name.get() != nil && IsThisIdentifier(node.name.get()) { return SubtreeContainsTypeScript } else { - return propagateModifierListSubtreeFacts(node.modifiers) | - propagateSubtreeFacts(node.name) | - propagateEraseableSyntaxSubtreeFacts(node.QuestionToken) | - propagateEraseableSyntaxSubtreeFacts(node.Type) | - propagateSubtreeFacts(node.Initializer) + return propagateModifierListSubtreeFacts(node.modifiers.get()) | + propagateSubtreeFacts(node.name.get()) | + propagateEraseableSyntaxSubtreeFacts(node.QuestionToken()) | + propagateEraseableSyntaxSubtreeFacts(node.Type()) | + propagateSubtreeFacts(node.Initializer()) } } @@ -1763,26 +1774,26 @@ func (node *ParameterDeclaration) propagateSubtreeFacts() SubtreeFacts { } func (node *BindingElement) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.PropertyName) | - propagateSubtreeFacts(node.name) | - propagateSubtreeFacts(node.Initializer) | - core.IfElse(node.DotDotDotToken != nil, SubtreeContainsRestOrSpread, SubtreeFactsNone) + return propagateSubtreeFacts(node.PropertyName()) | + propagateSubtreeFacts(node.name.get()) | + propagateSubtreeFacts(node.Initializer()) | + core.IfElse(node.DotDotDotToken() != nil, SubtreeContainsRestOrSpread, SubtreeFactsNone) } func (node *FunctionDeclaration) computeSubtreeFacts() SubtreeFacts { - if node.Body == nil || node.ModifierFlags()&ModifierFlagsAmbient != 0 { + if node.Body() == nil || node.ModifierFlags()&ModifierFlagsAmbient != 0 { return SubtreeContainsTypeScript } else { isAsync := node.ModifierFlags()&ModifierFlagsAsync != 0 - isGenerator := node.AsteriskToken != nil - return propagateModifierListSubtreeFacts(node.modifiers) | - propagateSubtreeFacts(node.AsteriskToken) | - propagateSubtreeFacts(node.name) | - propagateEraseableSyntaxListSubtreeFacts(node.TypeParameters) | - propagateNodeListSubtreeFacts(node.Parameters, propagateSubtreeFacts) | - propagateEraseableSyntaxSubtreeFacts(node.Type) | - propagateEraseableSyntaxSubtreeFacts(node.FullSignature) | - propagateSubtreeFacts(node.Body) | + isGenerator := node.AsteriskToken() != nil + return propagateModifierListSubtreeFacts(node.modifiers.get()) | + propagateSubtreeFacts(node.AsteriskToken()) | + propagateSubtreeFacts(node.name.get()) | + propagateEraseableSyntaxListSubtreeFacts(node.TypeParameters()) | + propagateNodeListSubtreeFacts(node.Parameters(), propagateSubtreeFacts) | + propagateEraseableSyntaxSubtreeFacts(node.Type()) | + propagateEraseableSyntaxSubtreeFacts(node.FullSignature()) | + propagateSubtreeFacts(node.Body()) | core.IfElse(isAsync && isGenerator, SubtreeContainsForAwaitOrAsyncGenerator, SubtreeFactsNone) | core.IfElse(isAsync && !isGenerator, SubtreeContainsAnyAwait, SubtreeFactsNone) } @@ -1794,19 +1805,19 @@ func (node *FunctionDeclaration) propagateSubtreeFacts() SubtreeFacts { // ClassLikeBase -func (node *ClassLikeBase) Name() *DeclarationName { return node.name } +func (node *ClassLikeBase) Name() *DeclarationName { return node.name.get() } func (node *ClassLikeBase) ClassLikeData() *ClassLikeBase { return node } func (node *ClassLikeBase) computeSubtreeFacts() SubtreeFacts { - if node.modifiers != nil && node.modifiers.ModifierFlags&ModifierFlagsAmbient != 0 { + if node.modifiers.get() != nil && node.modifiers.get().ModifierFlags&ModifierFlagsAmbient != 0 { return SubtreeContainsTypeScript } else { - return propagateModifierListSubtreeFacts(node.modifiers) | - propagateSubtreeFacts(node.name) | - propagateEraseableSyntaxListSubtreeFacts(node.TypeParameters) | - propagateNodeListSubtreeFacts(node.HeritageClauses, propagateSubtreeFacts) | - propagateNodeListSubtreeFacts(node.Members, propagateSubtreeFacts) + return propagateModifierListSubtreeFacts(node.modifiers.get()) | + propagateSubtreeFacts(node.name.get()) | + propagateEraseableSyntaxListSubtreeFacts(node.TypeParameters()) | + propagateNodeListSubtreeFacts(node.HeritageClauses(), propagateSubtreeFacts) | + propagateNodeListSubtreeFacts(node.Members(), propagateSubtreeFacts) } } @@ -1821,7 +1832,7 @@ func (node *ClassExpression) propagateSubtreeFacts() SubtreeFacts { func (node *HeritageClause) computeSubtreeFacts() SubtreeFacts { switch node.Token { case KindExtendsKeyword: - return propagateNodeListSubtreeFacts(node.Types, propagateSubtreeFacts) + return propagateNodeListSubtreeFacts(node.Types(), propagateSubtreeFacts) case KindImplementsKeyword: return SubtreeContainsTypeScript default: @@ -1834,18 +1845,18 @@ func IsTypeOrJSTypeAliasDeclaration(node *Node) bool { } func (node *EnumMember) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.name) | - propagateSubtreeFacts(node.Initializer) | + return propagateSubtreeFacts(node.name.get()) | + propagateSubtreeFacts(node.Initializer()) | SubtreeContainsTypeScript } func (node *EnumDeclaration) computeSubtreeFacts() SubtreeFacts { - if node.modifiers != nil && node.modifiers.ModifierFlags&ModifierFlagsAmbient != 0 { + if node.modifiers.get() != nil && node.modifiers.get().ModifierFlags&ModifierFlagsAmbient != 0 { return SubtreeContainsTypeScript } else { - return propagateModifierListSubtreeFacts(node.modifiers) | - propagateSubtreeFacts(node.name) | - propagateNodeListSubtreeFacts(node.Members, propagateSubtreeFacts) | + return propagateModifierListSubtreeFacts(node.modifiers.get()) | + propagateSubtreeFacts(node.name.get()) | + propagateNodeListSubtreeFacts(node.Members(), propagateSubtreeFacts) | SubtreeContainsTypeScript } } @@ -1854,9 +1865,9 @@ func (node *ModuleDeclaration) computeSubtreeFacts() SubtreeFacts { if node.ModifierFlags()&ModifierFlagsAmbient != 0 { return SubtreeContainsTypeScript } else { - return propagateModifierListSubtreeFacts(node.modifiers) | - propagateSubtreeFacts(node.name) | - propagateSubtreeFacts(node.Body) | + return propagateModifierListSubtreeFacts(node.modifiers.get()) | + propagateSubtreeFacts(node.name.get()) | + propagateSubtreeFacts(node.Body()) | SubtreeContainsTypeScript } } @@ -1866,12 +1877,12 @@ func (node *ModuleDeclaration) propagateSubtreeFacts() SubtreeFacts { } func (node *ImportEqualsDeclaration) computeSubtreeFacts() SubtreeFacts { - if node.IsTypeOnly || !IsExternalModuleReference(node.ModuleReference) { + if node.IsTypeOnly || !IsExternalModuleReference(node.ModuleReference()) { return SubtreeContainsTypeScript } else { - return propagateModifierListSubtreeFacts(node.modifiers) | - propagateSubtreeFacts(node.name) | - propagateSubtreeFacts(node.ModuleReference) + return propagateModifierListSubtreeFacts(node.modifiers.get()) | + propagateSubtreeFacts(node.name.get()) | + propagateSubtreeFacts(node.ModuleReference()) } } @@ -1883,8 +1894,8 @@ func (node *ImportSpecifier) computeSubtreeFacts() SubtreeFacts { if node.IsTypeOnly { return SubtreeContainsTypeScript } else { - return propagateSubtreeFacts(node.PropertyName) | - propagateSubtreeFacts(node.name) + return propagateSubtreeFacts(node.PropertyName()) | + propagateSubtreeFacts(node.name.get()) } } @@ -1892,13 +1903,13 @@ func (node *ImportClause) computeSubtreeFacts() SubtreeFacts { if node.PhaseModifier == KindTypeKeyword { return SubtreeContainsTypeScript } else { - return propagateSubtreeFacts(node.name) | - propagateSubtreeFacts(node.NamedBindings) + return propagateSubtreeFacts(node.name.get()) | + propagateSubtreeFacts(node.NamedBindings()) } } func (node *ExportAssignment) computeSubtreeFacts() SubtreeFacts { - return propagateModifierListSubtreeFacts(node.modifiers) | propagateSubtreeFacts(node.Type) | propagateSubtreeFacts(node.Expression) | core.IfElse(node.IsExportEquals, SubtreeContainsTypeScript, SubtreeFactsNone) + return propagateModifierListSubtreeFacts(node.modifiers.get()) | propagateSubtreeFacts(node.Type()) | propagateSubtreeFacts(node.Expression()) | core.IfElse(node.IsExportEquals, SubtreeContainsTypeScript, SubtreeFactsNone) } func IsAnyExportAssignment(node *Node) bool { @@ -1906,10 +1917,10 @@ func IsAnyExportAssignment(node *Node) bool { } func (node *ExportDeclaration) computeSubtreeFacts() SubtreeFacts { - return propagateModifierListSubtreeFacts(node.modifiers) | - propagateSubtreeFacts(node.ExportClause) | - propagateSubtreeFacts(node.ModuleSpecifier) | - propagateSubtreeFacts(node.Attributes) | + return propagateModifierListSubtreeFacts(node.modifiers.get()) | + propagateSubtreeFacts(node.ExportClause()) | + propagateSubtreeFacts(node.ModuleSpecifier()) | + propagateSubtreeFacts(node.Attributes()) | core.IfElse(node.IsTypeOnly, SubtreeContainsTypeScript, SubtreeFactsNone) } @@ -1917,27 +1928,27 @@ func (node *ExportSpecifier) computeSubtreeFacts() SubtreeFacts { if node.IsTypeOnly { return SubtreeContainsTypeScript } else { - return propagateSubtreeFacts(node.PropertyName) | - propagateSubtreeFacts(node.name) + return propagateSubtreeFacts(node.PropertyName()) | + propagateSubtreeFacts(node.name.get()) } } // NamedMemberBase -func (node *NamedMemberBase) Modifiers() *ModifierList { return node.modifiers } -func (node *NamedMemberBase) setModifiers(modifiers *ModifierList) { node.modifiers = modifiers } -func (node *NamedMemberBase) Name() *DeclarationName { return node.name } +func (node *NamedMemberBase) Modifiers() *ModifierList { return node.modifiers.get() } +func (node *NamedMemberBase) setModifiers(modifiers *ModifierList) { node.modifiers.set(modifiers) } +func (node *NamedMemberBase) Name() *DeclarationName { return node.name.get() } func (node *ConstructorDeclaration) computeSubtreeFacts() SubtreeFacts { - if node.Body == nil { + if node.Body() == nil { return SubtreeContainsTypeScript } else { - return propagateModifierListSubtreeFacts(node.modifiers) | - propagateEraseableSyntaxListSubtreeFacts(node.TypeParameters) | - propagateNodeListSubtreeFacts(node.Parameters, propagateSubtreeFacts) | - propagateEraseableSyntaxSubtreeFacts(node.Type) | - propagateEraseableSyntaxSubtreeFacts(node.FullSignature) | - propagateSubtreeFacts(node.Body) + return propagateModifierListSubtreeFacts(node.modifiers.get()) | + propagateEraseableSyntaxListSubtreeFacts(node.TypeParameters()) | + propagateNodeListSubtreeFacts(node.Parameters(), propagateSubtreeFacts) | + propagateEraseableSyntaxSubtreeFacts(node.Type()) | + propagateEraseableSyntaxSubtreeFacts(node.FullSignature()) | + propagateSubtreeFacts(node.Body()) } } @@ -1948,39 +1959,39 @@ func (node *ConstructorDeclaration) propagateSubtreeFacts() SubtreeFacts { func (node *AccessorDeclarationBase) IsAccessorDeclaration() {} func (node *AccessorDeclarationBase) computeSubtreeFacts() SubtreeFacts { - if node.Body == nil { + if node.Body() == nil { return SubtreeContainsTypeScript } else { - return propagateModifierListSubtreeFacts(node.modifiers) | - propagateSubtreeFacts(node.name) | - propagateEraseableSyntaxListSubtreeFacts(node.TypeParameters) | - propagateNodeListSubtreeFacts(node.Parameters, propagateSubtreeFacts) | - propagateEraseableSyntaxSubtreeFacts(node.Type) | - propagateEraseableSyntaxSubtreeFacts(node.FullSignature) | - propagateSubtreeFacts(node.Body) + return propagateModifierListSubtreeFacts(node.modifiers.get()) | + propagateSubtreeFacts(node.name.get()) | + propagateEraseableSyntaxListSubtreeFacts(node.TypeParameters()) | + propagateNodeListSubtreeFacts(node.Parameters(), propagateSubtreeFacts) | + propagateEraseableSyntaxSubtreeFacts(node.Type()) | + propagateEraseableSyntaxSubtreeFacts(node.FullSignature()) | + propagateSubtreeFacts(node.Body()) } } func (node *AccessorDeclarationBase) propagateSubtreeFacts() SubtreeFacts { return node.SubtreeFacts() & ^SubtreeExclusionsAccessor | - propagateSubtreeFacts(node.name) + propagateSubtreeFacts(node.name.get()) } func (node *MethodDeclaration) computeSubtreeFacts() SubtreeFacts { - if node.Body == nil { + if node.Body() == nil { return SubtreeContainsTypeScript } else { - isAsync := node.modifiers != nil && node.modifiers.ModifierFlags&ModifierFlagsAsync != 0 - isGenerator := node.AsteriskToken != nil - return propagateModifierListSubtreeFacts(node.modifiers) | - propagateSubtreeFacts(node.AsteriskToken) | - propagateSubtreeFacts(node.name) | - propagateEraseableSyntaxSubtreeFacts(node.PostfixToken) | - propagateEraseableSyntaxListSubtreeFacts(node.TypeParameters) | - propagateNodeListSubtreeFacts(node.Parameters, propagateSubtreeFacts) | - propagateSubtreeFacts(node.Body) | - propagateEraseableSyntaxSubtreeFacts(node.Type) | - propagateEraseableSyntaxSubtreeFacts(node.FullSignature) | + isAsync := node.modifiers.get() != nil && node.modifiers.get().ModifierFlags&ModifierFlagsAsync != 0 + isGenerator := node.AsteriskToken() != nil + return propagateModifierListSubtreeFacts(node.modifiers.get()) | + propagateSubtreeFacts(node.AsteriskToken()) | + propagateSubtreeFacts(node.name.get()) | + propagateEraseableSyntaxSubtreeFacts(node.PostfixToken()) | + propagateEraseableSyntaxListSubtreeFacts(node.TypeParameters()) | + propagateNodeListSubtreeFacts(node.Parameters(), propagateSubtreeFacts) | + propagateSubtreeFacts(node.Body()) | + propagateEraseableSyntaxSubtreeFacts(node.Type()) | + propagateEraseableSyntaxSubtreeFacts(node.FullSignature()) | core.IfElse(isAsync && isGenerator, SubtreeContainsForAwaitOrAsyncGenerator, SubtreeFactsNone) | core.IfElse(isAsync && !isGenerator, SubtreeContainsAnyAwait, SubtreeFactsNone) } @@ -1988,26 +1999,26 @@ func (node *MethodDeclaration) computeSubtreeFacts() SubtreeFacts { func (node *MethodDeclaration) propagateSubtreeFacts() SubtreeFacts { return node.SubtreeFacts() & ^SubtreeExclusionsMethod | - propagateSubtreeFacts(node.name) + propagateSubtreeFacts(node.name.get()) } func (node *PropertyDeclaration) computeSubtreeFacts() SubtreeFacts { - return propagateModifierListSubtreeFacts(node.modifiers) | - propagateSubtreeFacts(node.name) | - propagateEraseableSyntaxSubtreeFacts(node.PostfixToken) | - propagateEraseableSyntaxSubtreeFacts(node.Type) | - propagateSubtreeFacts(node.Initializer) | + return propagateModifierListSubtreeFacts(node.modifiers.get()) | + propagateSubtreeFacts(node.name.get()) | + propagateEraseableSyntaxSubtreeFacts(node.PostfixToken()) | + propagateEraseableSyntaxSubtreeFacts(node.Type()) | + propagateSubtreeFacts(node.Initializer()) | SubtreeContainsClassFields } func (node *PropertyDeclaration) propagateSubtreeFacts() SubtreeFacts { return node.SubtreeFacts() & ^SubtreeExclusionsProperty | - propagateSubtreeFacts(node.name) + propagateSubtreeFacts(node.name.get()) } func (node *ClassStaticBlockDeclaration) computeSubtreeFacts() SubtreeFacts { - return propagateModifierListSubtreeFacts(node.modifiers) | - propagateSubtreeFacts(node.Body) | + return propagateModifierListSubtreeFacts(node.modifiers.get()) | + propagateSubtreeFacts(node.Body()) | SubtreeContainsClassFields } @@ -2041,33 +2052,33 @@ func (node *NoSubstitutionTemplateLiteral) computeSubtreeFacts() SubtreeFacts { } func (node *BinaryExpression) computeSubtreeFacts() SubtreeFacts { - facts := propagateModifierListSubtreeFacts(node.modifiers) | - propagateSubtreeFacts(node.Left) | - propagateSubtreeFacts(node.Type) | - propagateSubtreeFacts(node.OperatorToken) | - propagateSubtreeFacts(node.Right) | - core.IfElse(node.OperatorToken.Kind == KindInKeyword && IsPrivateIdentifier(node.Left), SubtreeContainsClassFields|SubtreeContainsPrivateIdentifierInExpression, SubtreeFactsNone) - if node.OperatorToken.Kind == KindEqualsToken { - if (IsObjectLiteralExpression(node.Left) || IsArrayLiteralExpression(node.Left)) && ContainsObjectRestOrSpread(node.Left) { + facts := propagateModifierListSubtreeFacts(node.modifiers.get()) | + propagateSubtreeFacts(node.Left()) | + propagateSubtreeFacts(node.Type()) | + propagateSubtreeFacts(node.OperatorToken()) | + propagateSubtreeFacts(node.Right()) | + core.IfElse(node.OperatorToken().Kind == KindInKeyword && IsPrivateIdentifier(node.Left()), SubtreeContainsClassFields|SubtreeContainsPrivateIdentifierInExpression, SubtreeFactsNone) + if node.OperatorToken().Kind == KindEqualsToken { + if (IsObjectLiteralExpression(node.Left()) || IsArrayLiteralExpression(node.Left())) && ContainsObjectRestOrSpread(node.Left()) { facts |= SubtreeContainsObjectRestOrSpread } } return facts } -func (node *BinaryExpression) setModifiers(modifiers *ModifierList) { node.modifiers = modifiers } +func (node *BinaryExpression) setModifiers(modifiers *ModifierList) { node.modifiers.set(modifiers) } func (node *YieldExpression) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | SubtreeContainsForAwaitOrAsyncGenerator + return propagateSubtreeFacts(node.Expression()) | SubtreeContainsForAwaitOrAsyncGenerator } func (node *ArrowFunction) computeSubtreeFacts() SubtreeFacts { - return propagateModifierListSubtreeFacts(node.modifiers) | - propagateEraseableSyntaxListSubtreeFacts(node.TypeParameters) | - propagateNodeListSubtreeFacts(node.Parameters, propagateSubtreeFacts) | - propagateEraseableSyntaxSubtreeFacts(node.Type) | - propagateEraseableSyntaxSubtreeFacts(node.FullSignature) | - propagateSubtreeFacts(node.Body) | + return propagateModifierListSubtreeFacts(node.modifiers.get()) | + propagateEraseableSyntaxListSubtreeFacts(node.TypeParameters()) | + propagateNodeListSubtreeFacts(node.Parameters(), propagateSubtreeFacts) | + propagateEraseableSyntaxSubtreeFacts(node.Type()) | + propagateEraseableSyntaxSubtreeFacts(node.FullSignature()) | + propagateSubtreeFacts(node.Body()) | core.IfElse(node.ModifierFlags()&ModifierFlagsAsync != 0, SubtreeContainsAnyAwait, SubtreeFactsNone) } @@ -2076,16 +2087,16 @@ func (node *ArrowFunction) propagateSubtreeFacts() SubtreeFacts { } func (node *FunctionExpression) computeSubtreeFacts() SubtreeFacts { - isAsync := node.modifiers != nil && node.modifiers.ModifierFlags&ModifierFlagsAsync != 0 - isGenerator := node.AsteriskToken != nil - return propagateModifierListSubtreeFacts(node.modifiers) | - propagateSubtreeFacts(node.AsteriskToken) | - propagateSubtreeFacts(node.name) | - propagateEraseableSyntaxListSubtreeFacts(node.TypeParameters) | - propagateNodeListSubtreeFacts(node.Parameters, propagateSubtreeFacts) | - propagateEraseableSyntaxSubtreeFacts(node.Type) | - propagateEraseableSyntaxSubtreeFacts(node.FullSignature) | - propagateSubtreeFacts(node.Body) | + isAsync := node.modifiers.get() != nil && node.modifiers.get().ModifierFlags&ModifierFlagsAsync != 0 + isGenerator := node.AsteriskToken() != nil + return propagateModifierListSubtreeFacts(node.modifiers.get()) | + propagateSubtreeFacts(node.AsteriskToken()) | + propagateSubtreeFacts(node.name.get()) | + propagateEraseableSyntaxListSubtreeFacts(node.TypeParameters()) | + propagateNodeListSubtreeFacts(node.Parameters(), propagateSubtreeFacts) | + propagateEraseableSyntaxSubtreeFacts(node.Type()) | + propagateEraseableSyntaxSubtreeFacts(node.FullSignature()) | + propagateSubtreeFacts(node.Body()) | core.IfElse(isAsync && isGenerator, SubtreeContainsForAwaitOrAsyncGenerator, SubtreeFactsNone) | core.IfElse(isAsync && !isGenerator, SubtreeContainsAnyAwait, SubtreeFactsNone) } @@ -2095,7 +2106,7 @@ func (node *FunctionExpression) propagateSubtreeFacts() SubtreeFacts { } func (node *AsExpression) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | SubtreeContainsTypeScript + return propagateSubtreeFacts(node.Expression()) | SubtreeContainsTypeScript } func (node *AsExpression) propagateSubtreeFacts() SubtreeFacts { @@ -2103,7 +2114,7 @@ func (node *AsExpression) propagateSubtreeFacts() SubtreeFacts { } func (node *SatisfiesExpression) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | SubtreeContainsTypeScript + return propagateSubtreeFacts(node.Expression()) | SubtreeContainsTypeScript } func (node *SatisfiesExpression) propagateSubtreeFacts() SubtreeFacts { @@ -2112,12 +2123,12 @@ func (node *SatisfiesExpression) propagateSubtreeFacts() SubtreeFacts { func (node *PropertyAccessExpression) computeSubtreeFacts() SubtreeFacts { privateName := SubtreeFactsNone - if !IsIdentifier(node.name) { + if !IsIdentifier(node.name.get()) { privateName = SubtreeContainsPrivateIdentifierInExpression } - return propagateSubtreeFacts(node.Expression) | - propagateSubtreeFacts(node.QuestionDotToken) | - propagateSubtreeFacts(node.name) | privateName + return propagateSubtreeFacts(node.Expression()) | + propagateSubtreeFacts(node.QuestionDotToken()) | + propagateSubtreeFacts(node.name.get()) | privateName } func (node *PropertyAccessExpression) propagateSubtreeFacts() SubtreeFacts { @@ -2129,10 +2140,10 @@ func (node *ElementAccessExpression) propagateSubtreeFacts() SubtreeFacts { } func (node *CallExpression) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | - propagateSubtreeFacts(node.QuestionDotToken) | - propagateEraseableSyntaxListSubtreeFacts(node.TypeArguments) | - propagateNodeListSubtreeFacts(node.Arguments, propagateSubtreeFacts) | + return propagateSubtreeFacts(node.Expression()) | + propagateSubtreeFacts(node.QuestionDotToken()) | + propagateEraseableSyntaxListSubtreeFacts(node.TypeArguments()) | + propagateNodeListSubtreeFacts(node.Arguments(), propagateSubtreeFacts) | core.IfElse(IsImportCall(node.AsNode()), SubtreeContainsDynamicImport, SubtreeFactsNone) } @@ -2141,9 +2152,9 @@ func (node *CallExpression) propagateSubtreeFacts() SubtreeFacts { } func (node *NewExpression) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | - propagateEraseableSyntaxListSubtreeFacts(node.TypeArguments) | - propagateNodeListSubtreeFacts(node.Arguments, propagateSubtreeFacts) + return propagateSubtreeFacts(node.Expression()) | + propagateEraseableSyntaxListSubtreeFacts(node.TypeArguments()) | + propagateNodeListSubtreeFacts(node.Arguments(), propagateSubtreeFacts) } func (node *NewExpression) propagateSubtreeFacts() SubtreeFacts { @@ -2151,22 +2162,22 @@ func (node *NewExpression) propagateSubtreeFacts() SubtreeFacts { } func (node *MetaProperty) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.name) &^ SubtreeContainsIdentifier + return propagateSubtreeFacts(node.name.get()) &^ SubtreeContainsIdentifier } func (node *NonNullExpression) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | SubtreeContainsTypeScript + return propagateSubtreeFacts(node.Expression()) | SubtreeContainsTypeScript } func (node *SpreadElement) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | SubtreeContainsRestOrSpread + return propagateSubtreeFacts(node.Expression()) | SubtreeContainsRestOrSpread } func (node *TaggedTemplateExpression) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Tag) | - propagateSubtreeFacts(node.QuestionDotToken) | - propagateEraseableSyntaxListSubtreeFacts(node.TypeArguments) | - propagateSubtreeFacts(node.Template) + return propagateSubtreeFacts(node.Tag()) | + propagateSubtreeFacts(node.QuestionDotToken()) | + propagateEraseableSyntaxListSubtreeFacts(node.TypeArguments()) | + propagateSubtreeFacts(node.Template()) } // Hand-written subtree facts for nontrivial generated nodes. @@ -2180,29 +2191,29 @@ func (node *ObjectLiteralExpression) propagateSubtreeFacts() SubtreeFacts { } func (node *SpreadAssignment) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | SubtreeContainsESObjectRestOrSpread | SubtreeContainsObjectRestOrSpread + return propagateSubtreeFacts(node.Expression()) | SubtreeContainsESObjectRestOrSpread | SubtreeContainsObjectRestOrSpread } func (node *PropertyAssignment) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.name) | - propagateSubtreeFacts(node.Type) | - propagateSubtreeFacts(node.Initializer) + return propagateSubtreeFacts(node.name.get()) | + propagateSubtreeFacts(node.Type()) | + propagateSubtreeFacts(node.Initializer()) } func (node *ShorthandPropertyAssignment) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.name) | - propagateSubtreeFacts(node.Type) | - propagateSubtreeFacts(node.ObjectAssignmentInitializer) | + return propagateSubtreeFacts(node.name.get()) | + propagateSubtreeFacts(node.Type()) | + propagateSubtreeFacts(node.ObjectAssignmentInitializer()) | SubtreeContainsTypeScript } func (node *AwaitExpression) computeSubtreeFacts() SubtreeFacts { // await in an ES2018 async generator must use `yield __await(expr)` - return propagateSubtreeFacts(node.Expression) | SubtreeContainsAwait | SubtreeContainsAnyAwait | SubtreeContainsForAwaitOrAsyncGenerator + return propagateSubtreeFacts(node.Expression()) | SubtreeContainsAwait | SubtreeContainsAnyAwait | SubtreeContainsForAwaitOrAsyncGenerator } func (node *TypeAssertion) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | SubtreeContainsTypeScript + return propagateSubtreeFacts(node.Expression()) | SubtreeContainsTypeScript } func (node *TypeAssertion) propagateSubtreeFacts() SubtreeFacts { @@ -2210,8 +2221,8 @@ func (node *TypeAssertion) propagateSubtreeFacts() SubtreeFacts { } func (node *ExpressionWithTypeArguments) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | - propagateEraseableSyntaxListSubtreeFacts(node.TypeArguments) + return propagateSubtreeFacts(node.Expression()) | + propagateEraseableSyntaxListSubtreeFacts(node.TypeArguments()) } func (node *ImportAttributesNode) GetResolutionModeOverride(grammarErrorOnNode func(node *Node, message *diagnostics.Message, args ...any) bool) (core.ResolutionMode, bool) { @@ -2219,7 +2230,7 @@ func (node *ImportAttributesNode) GetResolutionModeOverride(grammarErrorOnNode f return core.ResolutionModeNone, false } - attributes := node.AsImportAttributes().Attributes + attributes := node.AsImportAttributes().Attributes() attribute := core.Find(attributes.Nodes, func(attribute *Node) bool { return attribute.Name().Text() == "resolution-mode" @@ -2229,16 +2240,16 @@ func (node *ImportAttributesNode) GetResolutionModeOverride(grammarErrorOnNode f } elem := attribute.AsImportAttribute() - if !IsStringLiteralLike(elem.Value) { + if !IsStringLiteralLike(elem.Value()) { return core.ResolutionModeNone, false } - if elem.Value.Text() != "import" && elem.Value.Text() != "require" { + if elem.Value().Text() != "import" && elem.Value().Text() != "require" { if grammarErrorOnNode != nil { - grammarErrorOnNode(elem.Value, diagnostics.X_resolution_mode_should_be_either_require_or_import) + grammarErrorOnNode(elem.Value(), diagnostics.X_resolution_mode_should_be_either_require_or_import) } return core.ResolutionModeNone, false } - if elem.Value.Text() == "import" { + if elem.Value().Text() == "import" { return core.ResolutionModeESM, true } else { return core.ModuleKindCommonJS, true @@ -2277,39 +2288,39 @@ func (node *TemplateTail) computeSubtreeFacts() SubtreeFacts { } func (node *JsxElement) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.OpeningElement) | - propagateNodeListSubtreeFacts(node.Children, propagateSubtreeFacts) | - propagateSubtreeFacts(node.ClosingElement) | + return propagateSubtreeFacts(node.OpeningElement()) | + propagateNodeListSubtreeFacts(node.Children(), propagateSubtreeFacts) | + propagateSubtreeFacts(node.ClosingElement()) | SubtreeContainsJsx } func (node *JsxAttributes) computeSubtreeFacts() SubtreeFacts { - return propagateNodeListSubtreeFacts(node.Properties, propagateSubtreeFacts) | + return propagateNodeListSubtreeFacts(node.Properties(), propagateSubtreeFacts) | SubtreeContainsJsx } func (node *JsxNamespacedName) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Namespace) | - propagateSubtreeFacts(node.name) | + return propagateSubtreeFacts(node.Namespace()) | + propagateSubtreeFacts(node.name.get()) | SubtreeContainsJsx } func (node *JsxOpeningElement) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.TagName) | - propagateEraseableSyntaxListSubtreeFacts(node.TypeArguments) | - propagateSubtreeFacts(node.Attributes) | + return propagateSubtreeFacts(node.TagName()) | + propagateEraseableSyntaxListSubtreeFacts(node.TypeArguments()) | + propagateSubtreeFacts(node.Attributes()) | SubtreeContainsJsx } func (node *JsxSelfClosingElement) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.TagName) | - propagateEraseableSyntaxListSubtreeFacts(node.TypeArguments) | - propagateSubtreeFacts(node.Attributes) | + return propagateSubtreeFacts(node.TagName()) | + propagateEraseableSyntaxListSubtreeFacts(node.TypeArguments()) | + propagateSubtreeFacts(node.Attributes()) | SubtreeContainsJsx } func (node *JsxFragment) computeSubtreeFacts() SubtreeFacts { - return propagateNodeListSubtreeFacts(node.Children, propagateSubtreeFacts) | + return propagateNodeListSubtreeFacts(node.Children(), propagateSubtreeFacts) | SubtreeContainsJsx } @@ -2322,21 +2333,21 @@ func (node *JsxClosingFragment) computeSubtreeFacts() SubtreeFacts { } func (node *JsxAttribute) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.name) | - propagateSubtreeFacts(node.Initializer) | + return propagateSubtreeFacts(node.name.get()) | + propagateSubtreeFacts(node.Initializer()) | SubtreeContainsJsx } func (node *JsxSpreadAttribute) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | SubtreeContainsJsx + return propagateSubtreeFacts(node.Expression()) | SubtreeContainsJsx } func (node *JsxClosingElement) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.TagName) | SubtreeContainsJsx + return propagateSubtreeFacts(node.TagName()) | SubtreeContainsJsx } func (node *JsxExpression) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | SubtreeContainsJsx + return propagateSubtreeFacts(node.Expression()) | SubtreeContainsJsx } func (node *JsxText) computeSubtreeFacts() SubtreeFacts { @@ -2450,6 +2461,7 @@ type SourceFile struct { CompositeBase // Fields set by NewSourceFile + arena *linkarena.Arena // the arena of the factory that created the file fileName tspath.RootedFilePath // For debugging convenience parseOptions SourceFileParseOptions text string @@ -2476,6 +2488,7 @@ type SourceFile struct { CommentDirectives []CommentDirective jsdocCache map[*Node][]*Node jsdocMu sync.RWMutex + lazyJSDocArena *linkarena.Arena // nodes of JSDoc parsed on demand; guarded by jsdocMu hasLazyJSDoc bool identifiersOnce sync.Once identifiers collections.Set[string] @@ -2524,13 +2537,40 @@ type SourceFile struct { } func (f *NodeFactory) NewSourceFile(opts SourceFileParseOptions, text string, statements *NodeList, endOfFileToken *TokenNode) *Node { + // A source file holds maps, locks and slices that change over its lifetime, so unlike + // other nodes it is an ordinary Go object. The nodes that have it as their parent are + // not, so the arena keeps the file alive for them. data := &SourceFile{} + data.arena = f.mem() + data.arena.Keep(unsafe.Pointer(data), unsafe.Sizeof(*data)) data.fileName = opts.FileName data.parseOptions = opts data.text = text data.Statements = statements data.EndOfFileToken = endOfFileToken - return f.newNode(KindSourceFile, data) + f.nodeCount++ + return newNode(KindSourceFile, data, f.hooks) +} + +// Arena returns the arena of the factory that created the file. For a parsed file this is +// the memory of all of its nodes. Whoever stores a pointer to a Go object in one of those +// nodes has to register the object with it (see package linkarena). +func (node *SourceFile) Arena() *linkarena.Arena { + return node.arena +} + +// VerifyArena checks, when verification is on (see package linkarena), that everything the +// nodes in the file's arena refer to is kept alive, and panics otherwise. +func (node *SourceFile) VerifyArena() { + if !linkarena.Verifying() { + return + } + verifyArena(node.arena, node.fileName.AsString()) + node.jsdocMu.Lock() + defer node.jsdocMu.Unlock() + if node.lazyJSDocArena != nil { + verifyArena(node.lazyJSDocArena, "JSDoc of "+node.fileName.AsString()) + } } func (node *SourceFile) ParseOptions() SourceFileParseOptions { @@ -2928,7 +2968,7 @@ func (node *SourceFile) GetOrCreateToken( } token := createToken(kind, node, pos, end, flags) token.Loc = loc - token.Parent = parent + token.SetParent(parent) node.tokenCache[key] = token return token } @@ -2998,7 +3038,7 @@ func (node *SourceFile) computeDeclarationMap() map[string][]*Node { lastDeclaration = declarations[len(declarations)-1] } // Check whether this declaration belongs to an "overload group". - if lastDeclaration != nil && node.Parent == lastDeclaration.Parent && node.Symbol() == lastDeclaration.Symbol() { + if lastDeclaration != nil && node.Parent() == lastDeclaration.Parent() && node.Symbol() == lastDeclaration.Symbol() { // Overwrite the last declaration if it was an overload and this one is an implementation. if node.Body() != nil && lastDeclaration.Body() == nil { declarations[len(declarations)-1] = node @@ -3039,7 +3079,7 @@ func (node *SourceFile) computeDeclarationMap() map[string][]*Node { case KindExportDeclaration: // Handle named exports case e.g.: // export {a, b as B} from "mod"; - exportClause := node.AsExportDeclaration().ExportClause + exportClause := node.AsExportDeclaration().ExportClause() if exportClause != nil { if IsNamedExports(exportClause) { for _, element := range exportClause.Elements() { @@ -3050,7 +3090,7 @@ func (node *SourceFile) computeDeclarationMap() map[string][]*Node { } } case KindImportDeclaration: - importClause := node.AsImportDeclaration().ImportClause + importClause := node.AsImportDeclaration().ImportClause() if importClause != nil { // Handle default import case e.g.: // import d from "mod"; @@ -3060,7 +3100,7 @@ func (node *SourceFile) computeDeclarationMap() map[string][]*Node { // Handle named bindings in imports e.g.: // import * as NS from "mod"; // import {a, b as B} from "mod"; - namedBindings := importClause.AsImportClause().NamedBindings + namedBindings := importClause.AsImportClause().NamedBindings() if namedBindings != nil { if namedBindings.Kind == KindNamespaceImport { addDeclaration(namedBindings) @@ -3170,22 +3210,14 @@ func (spec *PragmaSpecification) IsTripleSlash() bool { // child ordering. Generated code in ast_generated.go delegates to these. func forEachChild_JSDocParameterOrPropertyTag(node *JSDocParameterOrPropertyTag, v Visitor) bool { - return visit(v, node.TagName) || + return visit(v, node.TagName()) || (node.IsNameFirst && - (visit(v, node.name) || visit(v, node.TypeExpression))) || + (visit(v, node.name.get()) || visit(v, node.TypeExpression()))) || (!node.IsNameFirst && - (visit(v, node.TypeExpression) || visit(v, node.name))) || - visitNodeList(v, node.Comment) + (visit(v, node.TypeExpression()) || visit(v, node.name.get()))) || + visitNodeList(v, node.Comment()) } func visitEachChild_JSDocParameterOrPropertyTag(node *JSDocParameterOrPropertyTag, v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocParameterOrPropertyTag(node, v.visitNode(node.TagName), v.visitNode(node.name), node.IsBracketed, v.visitNode(node.TypeExpression), node.IsNameFirst, v.visitNodes(node.Comment)) -} - -func (f *NodeFactory) ReleaseArenas() { - *f = NodeFactory{ - hooks: f.hooks, - textCount: f.textCount, - nodeCount: f.nodeCount, - } + return v.Factory.UpdateJSDocParameterOrPropertyTag(node, v.visitNode(node.TagName()), v.visitNode(node.name.get()), node.IsBracketed, v.visitNode(node.TypeExpression()), node.IsNameFirst, v.visitNodes(node.Comment())) } diff --git a/tsc/internal/ast/ast_generated.go b/tsc/internal/ast/ast_generated.go index f1c27cfe8403e..e839f918c201c 100644 --- a/tsc/internal/ast/ast_generated.go +++ b/tsc/internal/ast/ast_generated.go @@ -6,6 +6,7 @@ import ( "sync/atomic" "github.com/microsoft/TypeScript/tsc/internal/core" + "github.com/microsoft/TypeScript/tsc/internal/linkarena" ) var ( @@ -18,55 +19,10 @@ var ( // ────────────────────────────────────────────────────────────────────── type NodeFactory struct { - hooks NodeFactoryHooks - arrayTypeNodeArena core.Arena[ArrayTypeNode] - binaryExpressionArena core.Arena[BinaryExpression] - blockArena core.Arena[Block] - callExpressionArena core.Arena[CallExpression] - conditionalExpressionArena core.Arena[ConditionalExpression] - constructSignatureDeclarationArena core.Arena[ConstructSignatureDeclaration] - elementAccessExpressionArena core.Arena[ElementAccessExpression] - expressionStatementArena core.Arena[ExpressionStatement] - expressionWithTypeArgumentsArena core.Arena[ExpressionWithTypeArguments] - functionDeclarationArena core.Arena[FunctionDeclaration] - functionTypeNodeArena core.Arena[FunctionTypeNode] - heritageClauseArena core.Arena[HeritageClause] - identifierArena core.Arena[Identifier] - ifStatementArena core.Arena[IfStatement] - importSpecifierArena core.Arena[ImportSpecifier] - indexedAccessTypeNodeArena core.Arena[IndexedAccessTypeNode] - interfaceDeclarationArena core.Arena[InterfaceDeclaration] - intersectionTypeNodeArena core.Arena[IntersectionTypeNode] - jsdocArena core.Arena[JSDoc] - jsdocDeprecatedTagArena core.Arena[JSDocDeprecatedTag] - jsdocTextArena core.Arena[JSDocText] - jsdocUnknownTagArena core.Arena[JSDocUnknownTag] - keywordExpressionArena core.Arena[KeywordExpression] - keywordTypeNodeArena core.Arena[KeywordTypeNode] - literalTypeNodeArena core.Arena[LiteralTypeNode] - methodSignatureDeclarationArena core.Arena[MethodSignatureDeclaration] - modifierListArena core.Arena[ModifierList] - nodeListArena core.Arena[NodeList] - numericLiteralArena core.Arena[NumericLiteral] - parameterDeclarationArena core.Arena[ParameterDeclaration] - parenthesizedExpressionArena core.Arena[ParenthesizedExpression] - parenthesizedTypeNodeArena core.Arena[ParenthesizedTypeNode] - prefixUnaryExpressionArena core.Arena[PrefixUnaryExpression] - propertyAccessExpressionArena core.Arena[PropertyAccessExpression] - propertyAssignmentArena core.Arena[PropertyAssignment] - propertySignatureDeclarationArena core.Arena[PropertySignatureDeclaration] - returnStatementArena core.Arena[ReturnStatement] - stringLiteralArena core.Arena[StringLiteral] - tokenArena core.Arena[Token] - typeAliasDeclarationArena core.Arena[TypeAliasDeclaration] - typeLiteralNodeArena core.Arena[TypeLiteralNode] - typeOperatorNodeArena core.Arena[TypeOperatorNode] - typeParameterDeclarationArena core.Arena[TypeParameterDeclaration] - typeReferenceNodeArena core.Arena[TypeReferenceNode] - unionTypeNodeArena core.Arena[UnionTypeNode] - variableDeclarationArena core.Arena[VariableDeclaration] - variableDeclarationListArena core.Arena[VariableDeclarationList] - variableStatementArena core.Arena[VariableStatement] + hooks NodeFactoryHooks + arena *linkarena.Arena // memory of the nodes the factory creates; see arena.go + parsing bool // every node handed to the factory was created by it + sourceText string // text whose substrings the arena keeps alive as a whole nodeCount int textCount int @@ -83,9 +39,13 @@ type StatementBase struct { type IterationStatementBase struct { StatementBase - Statement *Statement + statement link[Node] // *Statement } +func (node *IterationStatementBase) Statement() *Statement { return node.statement.get() } + +func (node *IterationStatementBase) SetStatement(statement *Statement) { node.statement.set(statement) } + type ExpressionBase struct { NodeBase } @@ -117,7 +77,13 @@ type TypeNodeBase struct { type NodeWithTypeArgumentsBase struct { TypeNodeBase - TypeArguments *TypeList // Optional + typeArguments link[NodeList] // *TypeList. Optional +} + +func (node *NodeWithTypeArgumentsBase) TypeArguments() *TypeList { return node.typeArguments.get() } + +func (node *NodeWithTypeArgumentsBase) SetTypeArguments(typeArguments *TypeList) { + node.typeArguments.set(typeArguments) } type JSDocTypeBase struct { @@ -133,7 +99,7 @@ type ExportableBase struct { } type ModifiersBase struct { - modifiers *ModifierList // Optional + modifiers link[ModifierList] // *ModifierList. Optional } type LocalsContainerBase struct { @@ -153,18 +119,50 @@ type TypeSyntaxBase struct{} type FunctionLikeBase struct { LocalsContainerBase - TypeParameters *TypeParameterList // Optional - Parameters *ParameterList - Type *TypeNode // Optional - FullSignature *TypeNode // Optional + typeParameters link[NodeList] // *TypeParameterList. Optional + parameters link[NodeList] // *ParameterList + typeNode link[Node] // *TypeNode. Optional + fullSignature link[Node] // *TypeNode. Optional +} + +func (node *FunctionLikeBase) TypeParameters() *TypeParameterList { return node.typeParameters.get() } + +func (node *FunctionLikeBase) SetTypeParameters(typeParameters *TypeParameterList) { + node.typeParameters.set(typeParameters) +} + +func (node *FunctionLikeBase) Parameters() *ParameterList { return node.parameters.get() } + +func (node *FunctionLikeBase) SetParameters(parameters *ParameterList) { + node.parameters.set(parameters) +} + +func (node *FunctionLikeBase) Type() *TypeNode { return node.typeNode.get() } + +func (node *FunctionLikeBase) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + +func (node *FunctionLikeBase) FullSignature() *TypeNode { return node.fullSignature.get() } + +func (node *FunctionLikeBase) SetFullSignature(fullSignature *TypeNode) { + node.fullSignature.set(fullSignature) } type BodyBase struct { - AsteriskToken *AsteriskToken // Optional - Body *NodeBody // Optional + asteriskToken link[Node] // *AsteriskToken. Optional + body link[Node] // *NodeBody. Optional EndFlowNode *FlowNode } +func (node *BodyBase) AsteriskToken() *AsteriskToken { return node.asteriskToken.get() } + +func (node *BodyBase) SetAsteriskToken(asteriskToken *AsteriskToken) { + node.asteriskToken.set(asteriskToken) +} + +func (node *BodyBase) Body() *NodeBody { return node.body.get() } + +func (node *BodyBase) SetBody(body *NodeBody) { node.body.set(body) } + type FunctionLikeWithBodyBase struct { FunctionLikeBase BodyBase @@ -175,12 +173,28 @@ type ClassLikeBase struct { ModifiersBase LocalsContainerBase CompositeBase - name *IdentifierNode // Optional - TypeParameters *TypeParameterList // Optional - HeritageClauses *HeritageClauseList // Optional - Members *ClassElementList + name link[Node] // *IdentifierNode. Optional + typeParameters link[NodeList] // *TypeParameterList. Optional + heritageClauses link[NodeList] // *HeritageClauseList. Optional + members link[NodeList] // *ClassElementList +} + +func (node *ClassLikeBase) TypeParameters() *TypeParameterList { return node.typeParameters.get() } + +func (node *ClassLikeBase) SetTypeParameters(typeParameters *TypeParameterList) { + node.typeParameters.set(typeParameters) } +func (node *ClassLikeBase) HeritageClauses() *HeritageClauseList { return node.heritageClauses.get() } + +func (node *ClassLikeBase) SetHeritageClauses(heritageClauses *HeritageClauseList) { + node.heritageClauses.set(heritageClauses) +} + +func (node *ClassLikeBase) Members() *ClassElementList { return node.members.get() } + +func (node *ClassLikeBase) SetMembers(members *ClassElementList) { node.members.set(members) } + type LiteralLikeNodeBase struct { Text string TokenFlags TokenFlags @@ -203,8 +217,14 @@ type ClassElementBase struct{} type NamedMemberBase struct { ModifiersBase - name *PropertyName - PostfixToken *TokenNode // Optional + name link[Node] // *PropertyName + postfixToken link[Node] // *TokenNode. Optional +} + +func (node *NamedMemberBase) PostfixToken() *TokenNode { return node.postfixToken.get() } + +func (node *NamedMemberBase) SetPostfixToken(postfixToken *TokenNode) { + node.postfixToken.set(postfixToken) } type ObjectLiteralElementBase struct{} @@ -230,15 +250,27 @@ type FunctionOrConstructorTypeNodeBase struct { type UnionOrIntersectionTypeNodeBase struct { TypeNodeBase - Types *TypeList + types link[NodeList] // *TypeList } +func (node *UnionOrIntersectionTypeNodeBase) Types() *TypeList { return node.types.get() } + +func (node *UnionOrIntersectionTypeNodeBase) SetTypes(types *TypeList) { node.types.set(types) } + type JSDocTagBase struct { NodeBase - TagName *IdentifierNode - Comment *NodeList // Optional + tagName link[Node] // *IdentifierNode + comment link[NodeList] // *NodeList. Optional } +func (node *JSDocTagBase) TagName() *IdentifierNode { return node.tagName.get() } + +func (node *JSDocTagBase) SetTagName(tagName *IdentifierNode) { node.tagName.set(tagName) } + +func (node *JSDocTagBase) Comment() *NodeList { return node.comment.get() } + +func (node *JSDocTagBase) SetComment(comment *NodeList) { node.comment.set(comment) } + type JSDocCommentBase struct { NodeBase text []string @@ -598,7 +630,7 @@ type Token struct { } func (f *NodeFactory) NewToken(kind TokenSyntaxKind) *Node { - data := f.tokenArena.New() + data := newData[Token](f) return f.newNode(kind, data) } @@ -625,8 +657,9 @@ type Identifier struct { } func (f *NodeFactory) NewIdentifier(text string) *Node { - data := f.identifierArena.New() + data := newData[Identifier](f) data.Text = text + f.keepString(text) f.textCount++ return f.newNode(KindIdentifier, data) } @@ -649,8 +682,9 @@ type PrivateIdentifier struct { } func (f *NodeFactory) NewPrivateIdentifier(text string) *Node { - data := &PrivateIdentifier{} + data := newData[PrivateIdentifier](f) data.Text = text + f.keepString(text) f.textCount++ return f.newNode(KindPrivateIdentifier, data) } @@ -671,39 +705,47 @@ type QualifiedName struct { NodeBase FlowNodeBase CompositeBase - Left *EntityName - Right *MemberName + left link[Node] // *EntityName + right link[Node] // *MemberName } +func (node *QualifiedName) Left() *EntityName { return node.left.get() } + +func (node *QualifiedName) SetLeft(left *EntityName) { node.left.set(left) } + +func (node *QualifiedName) Right() *MemberName { return node.right.get() } + +func (node *QualifiedName) SetRight(right *MemberName) { node.right.set(right) } + func (f *NodeFactory) NewQualifiedName(left *EntityName, right *MemberName) *Node { - data := &QualifiedName{} - data.Left = left - data.Right = right + data := newData[QualifiedName](f) + data.left.set(left) + data.right.set(right) return f.newNode(KindQualifiedName, data) } func (f *NodeFactory) UpdateQualifiedName(node *QualifiedName, left *EntityName, right *MemberName) *Node { - if left != node.Left || right != node.Right { + if left != node.Left() || right != node.Right() { return updateNode(f.NewQualifiedName(left, right), node.AsNode(), f.hooks) } return node.AsNode() } func (node *QualifiedName) ForEachChild(v Visitor) bool { - return visit(v, node.Left) || visit(v, node.Right) + return visit(v, node.Left()) || visit(v, node.Right()) } func (node *QualifiedName) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateQualifiedName(node, v.visitNode(node.Left), v.visitNode(node.Right)) + return v.Factory.UpdateQualifiedName(node, v.visitNode(node.Left()), v.visitNode(node.Right())) } func (node *QualifiedName) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewQualifiedName(node.Left, node.Right), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewQualifiedName(node.Left(), node.Right()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *QualifiedName) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Left) | - propagateSubtreeFacts(node.Right) + return propagateSubtreeFacts(node.Left()) | + propagateSubtreeFacts(node.Right()) } func IsQualifiedName(node *Node) bool { @@ -717,36 +759,42 @@ func IsQualifiedName(node *Node) bool { type ComputedPropertyName struct { NodeBase CompositeBase - Expression *Expression + expression link[Node] // *Expression +} + +func (node *ComputedPropertyName) Expression() *Expression { return node.expression.get() } + +func (node *ComputedPropertyName) SetExpression(expression *Expression) { + node.expression.set(expression) } func (f *NodeFactory) NewComputedPropertyName(expression *Expression) *Node { - data := &ComputedPropertyName{} - data.Expression = expression + data := newData[ComputedPropertyName](f) + data.expression.set(expression) return f.newNode(KindComputedPropertyName, data) } func (f *NodeFactory) UpdateComputedPropertyName(node *ComputedPropertyName, expression *Expression) *Node { - if expression != node.Expression { + if expression != node.Expression() { return updateNode(f.NewComputedPropertyName(expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ComputedPropertyName) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) + return visit(v, node.Expression()) } func (node *ComputedPropertyName) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateComputedPropertyName(node, v.visitNode(node.Expression)) + return v.Factory.UpdateComputedPropertyName(node, v.visitNode(node.Expression())) } func (node *ComputedPropertyName) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewComputedPropertyName(node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewComputedPropertyName(node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ComputedPropertyName) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) + return propagateSubtreeFacts(node.Expression()) } func IsComputedPropertyName(node *Node) bool { @@ -760,32 +808,38 @@ func IsComputedPropertyName(node *Node) bool { type Decorator struct { NodeBase CompositeBase - Expression *LeftHandSideExpression + expression link[Node] // *LeftHandSideExpression +} + +func (node *Decorator) Expression() *LeftHandSideExpression { return node.expression.get() } + +func (node *Decorator) SetExpression(expression *LeftHandSideExpression) { + node.expression.set(expression) } func (f *NodeFactory) NewDecorator(expression *LeftHandSideExpression) *Node { - data := &Decorator{} - data.Expression = expression + data := newData[Decorator](f) + data.expression.set(expression) return f.newNode(KindDecorator, data) } func (f *NodeFactory) UpdateDecorator(node *Decorator, expression *LeftHandSideExpression) *Node { - if expression != node.Expression { + if expression != node.Expression() { return updateNode(f.NewDecorator(expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *Decorator) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) + return visit(v, node.Expression()) } func (node *Decorator) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateDecorator(node, v.visitNode(node.Expression)) + return v.Factory.UpdateDecorator(node, v.visitNode(node.Expression())) } func (node *Decorator) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewDecorator(node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewDecorator(node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func IsDecorator(node *Node) bool { @@ -801,7 +855,7 @@ type EmptyStatement struct { } func (f *NodeFactory) NewEmptyStatement() *Node { - data := &EmptyStatement{} + data := newData[EmptyStatement](f) return f.newNode(KindEmptyStatement, data) } @@ -820,42 +874,58 @@ func IsEmptyStatement(node *Node) bool { type IfStatement struct { StatementBase CompositeBase - Expression *Expression - ThenStatement *Statement - ElseStatement *Statement // Optional + expression link[Node] // *Expression + thenStatement link[Node] // *Statement + elseStatement link[Node] // *Statement. Optional +} + +func (node *IfStatement) Expression() *Expression { return node.expression.get() } + +func (node *IfStatement) SetExpression(expression *Expression) { node.expression.set(expression) } + +func (node *IfStatement) ThenStatement() *Statement { return node.thenStatement.get() } + +func (node *IfStatement) SetThenStatement(thenStatement *Statement) { + node.thenStatement.set(thenStatement) +} + +func (node *IfStatement) ElseStatement() *Statement { return node.elseStatement.get() } + +func (node *IfStatement) SetElseStatement(elseStatement *Statement) { + node.elseStatement.set(elseStatement) } func (f *NodeFactory) NewIfStatement(expression *Expression, thenStatement *Statement, elseStatement *Statement) *Node { - data := f.ifStatementArena.New() - data.Expression = expression - data.ThenStatement = thenStatement - data.ElseStatement = elseStatement + data := newData[IfStatement](f) + data.expression.set(expression) + data.thenStatement.set(thenStatement) + data.elseStatement.set(elseStatement) return f.newNode(KindIfStatement, data) } func (f *NodeFactory) UpdateIfStatement(node *IfStatement, expression *Expression, thenStatement *Statement, elseStatement *Statement) *Node { - if expression != node.Expression || thenStatement != node.ThenStatement || elseStatement != node.ElseStatement { + if expression != node.Expression() || thenStatement != node.ThenStatement() || elseStatement != node.ElseStatement() { return updateNode(f.NewIfStatement(expression, thenStatement, elseStatement), node.AsNode(), f.hooks) } return node.AsNode() } func (node *IfStatement) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) || visit(v, node.ThenStatement) || visit(v, node.ElseStatement) + return visit(v, node.Expression()) || visit(v, node.ThenStatement()) || visit(v, node.ElseStatement()) } func (node *IfStatement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateIfStatement(node, v.visitNode(node.Expression), v.visitEmbeddedStatement(node.ThenStatement), v.visitEmbeddedStatement(node.ElseStatement)) + return v.Factory.UpdateIfStatement(node, v.visitNode(node.Expression()), v.visitEmbeddedStatement(node.ThenStatement()), v.visitEmbeddedStatement(node.ElseStatement())) } func (node *IfStatement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewIfStatement(node.Expression, node.ThenStatement, node.ElseStatement), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewIfStatement(node.Expression(), node.ThenStatement(), node.ElseStatement()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *IfStatement) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | - propagateSubtreeFacts(node.ThenStatement) | - propagateSubtreeFacts(node.ElseStatement) + return propagateSubtreeFacts(node.Expression()) | + propagateSubtreeFacts(node.ThenStatement()) | + propagateSubtreeFacts(node.ElseStatement()) } func IsIfStatement(node *Node) bool { @@ -869,38 +939,42 @@ func IsIfStatement(node *Node) bool { type DoStatement struct { IterationStatementBase CompositeBase - Expression *Expression + expression link[Node] // *Expression } +func (node *DoStatement) Expression() *Expression { return node.expression.get() } + +func (node *DoStatement) SetExpression(expression *Expression) { node.expression.set(expression) } + func (f *NodeFactory) NewDoStatement(statement *Statement, expression *Expression) *Node { - data := &DoStatement{} - data.Statement = statement - data.Expression = expression + data := newData[DoStatement](f) + data.statement.set(statement) + data.expression.set(expression) return f.newNode(KindDoStatement, data) } func (f *NodeFactory) UpdateDoStatement(node *DoStatement, statement *Statement, expression *Expression) *Node { - if statement != node.Statement || expression != node.Expression { + if statement != node.Statement() || expression != node.Expression() { return updateNode(f.NewDoStatement(statement, expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *DoStatement) ForEachChild(v Visitor) bool { - return visit(v, node.Statement) || visit(v, node.Expression) + return visit(v, node.Statement()) || visit(v, node.Expression()) } func (node *DoStatement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateDoStatement(node, v.visitIterationBody(node.Statement), v.visitNode(node.Expression)) + return v.Factory.UpdateDoStatement(node, v.visitIterationBody(node.Statement()), v.visitNode(node.Expression())) } func (node *DoStatement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewDoStatement(node.Statement, node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewDoStatement(node.Statement(), node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *DoStatement) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Statement) | - propagateSubtreeFacts(node.Expression) + return propagateSubtreeFacts(node.Statement()) | + propagateSubtreeFacts(node.Expression()) } func IsDoStatement(node *Node) bool { @@ -914,38 +988,42 @@ func IsDoStatement(node *Node) bool { type WhileStatement struct { IterationStatementBase CompositeBase - Expression *Expression + expression link[Node] // *Expression } +func (node *WhileStatement) Expression() *Expression { return node.expression.get() } + +func (node *WhileStatement) SetExpression(expression *Expression) { node.expression.set(expression) } + func (f *NodeFactory) NewWhileStatement(expression *Expression, statement *Statement) *Node { - data := &WhileStatement{} - data.Expression = expression - data.Statement = statement + data := newData[WhileStatement](f) + data.expression.set(expression) + data.statement.set(statement) return f.newNode(KindWhileStatement, data) } func (f *NodeFactory) UpdateWhileStatement(node *WhileStatement, expression *Expression, statement *Statement) *Node { - if expression != node.Expression || statement != node.Statement { + if expression != node.Expression() || statement != node.Statement() { return updateNode(f.NewWhileStatement(expression, statement), node.AsNode(), f.hooks) } return node.AsNode() } func (node *WhileStatement) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) || visit(v, node.Statement) + return visit(v, node.Expression()) || visit(v, node.Statement()) } func (node *WhileStatement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateWhileStatement(node, v.visitNode(node.Expression), v.visitIterationBody(node.Statement)) + return v.Factory.UpdateWhileStatement(node, v.visitNode(node.Expression()), v.visitIterationBody(node.Statement())) } func (node *WhileStatement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewWhileStatement(node.Expression, node.Statement), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewWhileStatement(node.Expression(), node.Statement()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *WhileStatement) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | - propagateSubtreeFacts(node.Statement) + return propagateSubtreeFacts(node.Expression()) | + propagateSubtreeFacts(node.Statement()) } func IsWhileStatement(node *Node) bool { @@ -960,47 +1038,61 @@ type ForStatement struct { IterationStatementBase LocalsContainerBase CompositeBase - Initializer *ForInitializer // Optional - Condition *Expression // Optional - Incrementor *Expression // Optional + initializer link[Node] // *ForInitializer. Optional + condition link[Node] // *Expression. Optional + incrementor link[Node] // *Expression. Optional } +func (node *ForStatement) Initializer() *ForInitializer { return node.initializer.get() } + +func (node *ForStatement) SetInitializer(initializer *ForInitializer) { + node.initializer.set(initializer) +} + +func (node *ForStatement) Condition() *Expression { return node.condition.get() } + +func (node *ForStatement) SetCondition(condition *Expression) { node.condition.set(condition) } + +func (node *ForStatement) Incrementor() *Expression { return node.incrementor.get() } + +func (node *ForStatement) SetIncrementor(incrementor *Expression) { node.incrementor.set(incrementor) } + func (f *NodeFactory) NewForStatement(initializer *ForInitializer, condition *Expression, incrementor *Expression, statement *Statement) *Node { - data := &ForStatement{} - data.Initializer = initializer - data.Condition = condition - data.Incrementor = incrementor - data.Statement = statement + data := newData[ForStatement](f) + data.initializer.set(initializer) + data.condition.set(condition) + data.incrementor.set(incrementor) + data.statement.set(statement) return f.newNode(KindForStatement, data) } func (f *NodeFactory) UpdateForStatement(node *ForStatement, initializer *ForInitializer, condition *Expression, incrementor *Expression, statement *Statement) *Node { - if initializer != node.Initializer || condition != node.Condition || incrementor != node.Incrementor || statement != node.Statement { + if initializer != node.Initializer() || condition != node.Condition() || incrementor != node.Incrementor() || statement != node.Statement() { return updateNode(f.NewForStatement(initializer, condition, incrementor, statement), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ForStatement) ForEachChild(v Visitor) bool { - return visit(v, node.Initializer) || - visit(v, node.Condition) || - visit(v, node.Incrementor) || - visit(v, node.Statement) + return visit(v, node.Initializer()) || + visit(v, node.Condition()) || + visit(v, node.Incrementor()) || + visit(v, node.Statement()) } func (node *ForStatement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateForStatement(node, v.visitNode(node.Initializer), v.visitNode(node.Condition), v.visitNode(node.Incrementor), v.visitIterationBody(node.Statement)) + return v.Factory.UpdateForStatement(node, v.visitNode(node.Initializer()), v.visitNode(node.Condition()), v.visitNode(node.Incrementor()), v.visitIterationBody(node.Statement())) } func (node *ForStatement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewForStatement(node.Initializer, node.Condition, node.Incrementor, node.Statement), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewForStatement(node.Initializer(), node.Condition(), node.Incrementor(), node.Statement()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ForStatement) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Initializer) | - propagateSubtreeFacts(node.Condition) | - propagateSubtreeFacts(node.Incrementor) | - propagateSubtreeFacts(node.Statement) + return propagateSubtreeFacts(node.Initializer()) | + propagateSubtreeFacts(node.Condition()) | + propagateSubtreeFacts(node.Incrementor()) | + propagateSubtreeFacts(node.Statement()) } func IsForStatement(node *Node) bool { @@ -1015,41 +1107,63 @@ type ForInOrOfStatement struct { StatementBase LocalsContainerBase CompositeBase - AwaitModifier *AwaitKeyword // Optional - Initializer *ForInitializer - Expression *Expression - Statement *Statement + awaitModifier link[Node] // *AwaitKeyword. Optional + initializer link[Node] // *ForInitializer + expression link[Node] // *Expression + statement link[Node] // *Statement +} + +func (node *ForInOrOfStatement) AwaitModifier() *AwaitKeyword { return node.awaitModifier.get() } + +func (node *ForInOrOfStatement) SetAwaitModifier(awaitModifier *AwaitKeyword) { + node.awaitModifier.set(awaitModifier) +} + +func (node *ForInOrOfStatement) Initializer() *ForInitializer { return node.initializer.get() } + +func (node *ForInOrOfStatement) SetInitializer(initializer *ForInitializer) { + node.initializer.set(initializer) +} + +func (node *ForInOrOfStatement) Expression() *Expression { return node.expression.get() } + +func (node *ForInOrOfStatement) SetExpression(expression *Expression) { + node.expression.set(expression) } +func (node *ForInOrOfStatement) Statement() *Statement { return node.statement.get() } + +func (node *ForInOrOfStatement) SetStatement(statement *Statement) { node.statement.set(statement) } + func (f *NodeFactory) NewForInOrOfStatement(kind Kind, awaitModifier *AwaitKeyword, initializer *ForInitializer, expression *Expression, statement *Statement) *Node { - data := &ForInOrOfStatement{} - data.AwaitModifier = awaitModifier - data.Initializer = initializer - data.Expression = expression - data.Statement = statement + data := newData[ForInOrOfStatement](f) + data.awaitModifier.set(awaitModifier) + data.initializer.set(initializer) + data.expression.set(expression) + data.statement.set(statement) return f.newNode(kind, data) } func (f *NodeFactory) UpdateForInOrOfStatement(node *ForInOrOfStatement, awaitModifier *AwaitKeyword, initializer *ForInitializer, expression *Expression, statement *Statement) *Node { - if awaitModifier != node.AwaitModifier || initializer != node.Initializer || expression != node.Expression || statement != node.Statement { + if awaitModifier != node.AwaitModifier() || initializer != node.Initializer() || expression != node.Expression() || statement != node.Statement() { return updateNode(f.NewForInOrOfStatement(node.Kind, awaitModifier, initializer, expression, statement), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ForInOrOfStatement) ForEachChild(v Visitor) bool { - return visit(v, node.AwaitModifier) || - visit(v, node.Initializer) || - visit(v, node.Expression) || - visit(v, node.Statement) + return visit(v, node.AwaitModifier()) || + visit(v, node.Initializer()) || + visit(v, node.Expression()) || + visit(v, node.Statement()) } func (node *ForInOrOfStatement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateForInOrOfStatement(node, v.visitNode(node.AwaitModifier), v.visitNode(node.Initializer), v.visitNode(node.Expression), v.visitIterationBody(node.Statement)) + return v.Factory.UpdateForInOrOfStatement(node, v.visitNode(node.AwaitModifier()), v.visitNode(node.Initializer()), v.visitNode(node.Expression()), v.visitIterationBody(node.Statement())) } func (node *ForInOrOfStatement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewForInOrOfStatement(node.Kind, node.AwaitModifier, node.Initializer, node.Expression, node.Statement), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewForInOrOfStatement(node.Kind, node.AwaitModifier(), node.Initializer(), node.Expression(), node.Statement()), node.AsNode(), f.AsNodeFactory().hooks) } func IsForInStatement(node *Node) bool { @@ -1066,32 +1180,36 @@ func IsForOfStatement(node *Node) bool { type BreakStatement struct { StatementBase - Label *IdentifierNode // Optional + label link[Node] // *IdentifierNode. Optional } +func (node *BreakStatement) Label() *IdentifierNode { return node.label.get() } + +func (node *BreakStatement) SetLabel(label *IdentifierNode) { node.label.set(label) } + func (f *NodeFactory) NewBreakStatement(label *IdentifierNode) *Node { - data := &BreakStatement{} - data.Label = label + data := newData[BreakStatement](f) + data.label.set(label) return f.newNode(KindBreakStatement, data) } func (f *NodeFactory) UpdateBreakStatement(node *BreakStatement, label *IdentifierNode) *Node { - if label != node.Label { + if label != node.Label() { return updateNode(f.NewBreakStatement(label), node.AsNode(), f.hooks) } return node.AsNode() } func (node *BreakStatement) ForEachChild(v Visitor) bool { - return visit(v, node.Label) + return visit(v, node.Label()) } func (node *BreakStatement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateBreakStatement(node, v.visitNode(node.Label)) + return v.Factory.UpdateBreakStatement(node, v.visitNode(node.Label())) } func (node *BreakStatement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewBreakStatement(node.Label), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewBreakStatement(node.Label()), node.AsNode(), f.AsNodeFactory().hooks) } func IsBreakStatement(node *Node) bool { @@ -1104,32 +1222,36 @@ func IsBreakStatement(node *Node) bool { type ContinueStatement struct { StatementBase - Label *IdentifierNode // Optional + label link[Node] // *IdentifierNode. Optional } +func (node *ContinueStatement) Label() *IdentifierNode { return node.label.get() } + +func (node *ContinueStatement) SetLabel(label *IdentifierNode) { node.label.set(label) } + func (f *NodeFactory) NewContinueStatement(label *IdentifierNode) *Node { - data := &ContinueStatement{} - data.Label = label + data := newData[ContinueStatement](f) + data.label.set(label) return f.newNode(KindContinueStatement, data) } func (f *NodeFactory) UpdateContinueStatement(node *ContinueStatement, label *IdentifierNode) *Node { - if label != node.Label { + if label != node.Label() { return updateNode(f.NewContinueStatement(label), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ContinueStatement) ForEachChild(v Visitor) bool { - return visit(v, node.Label) + return visit(v, node.Label()) } func (node *ContinueStatement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateContinueStatement(node, v.visitNode(node.Label)) + return v.Factory.UpdateContinueStatement(node, v.visitNode(node.Label())) } func (node *ContinueStatement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewContinueStatement(node.Label), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewContinueStatement(node.Label()), node.AsNode(), f.AsNodeFactory().hooks) } func IsContinueStatement(node *Node) bool { @@ -1143,32 +1265,36 @@ func IsContinueStatement(node *Node) bool { type ReturnStatement struct { StatementBase CompositeBase - Expression *Expression // Optional + expression link[Node] // *Expression. Optional } +func (node *ReturnStatement) Expression() *Expression { return node.expression.get() } + +func (node *ReturnStatement) SetExpression(expression *Expression) { node.expression.set(expression) } + func (f *NodeFactory) NewReturnStatement(expression *Expression) *Node { - data := f.returnStatementArena.New() - data.Expression = expression + data := newData[ReturnStatement](f) + data.expression.set(expression) return f.newNode(KindReturnStatement, data) } func (f *NodeFactory) UpdateReturnStatement(node *ReturnStatement, expression *Expression) *Node { - if expression != node.Expression { + if expression != node.Expression() { return updateNode(f.NewReturnStatement(expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ReturnStatement) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) + return visit(v, node.Expression()) } func (node *ReturnStatement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateReturnStatement(node, v.visitNode(node.Expression)) + return v.Factory.UpdateReturnStatement(node, v.visitNode(node.Expression())) } func (node *ReturnStatement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewReturnStatement(node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewReturnStatement(node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func IsReturnStatement(node *Node) bool { @@ -1182,39 +1308,47 @@ func IsReturnStatement(node *Node) bool { type WithStatement struct { StatementBase CompositeBase - Expression *Expression - Statement *Statement + expression link[Node] // *Expression + statement link[Node] // *Statement } +func (node *WithStatement) Expression() *Expression { return node.expression.get() } + +func (node *WithStatement) SetExpression(expression *Expression) { node.expression.set(expression) } + +func (node *WithStatement) Statement() *Statement { return node.statement.get() } + +func (node *WithStatement) SetStatement(statement *Statement) { node.statement.set(statement) } + func (f *NodeFactory) NewWithStatement(expression *Expression, statement *Statement) *Node { - data := &WithStatement{} - data.Expression = expression - data.Statement = statement + data := newData[WithStatement](f) + data.expression.set(expression) + data.statement.set(statement) return f.newNode(KindWithStatement, data) } func (f *NodeFactory) UpdateWithStatement(node *WithStatement, expression *Expression, statement *Statement) *Node { - if expression != node.Expression || statement != node.Statement { + if expression != node.Expression() || statement != node.Statement() { return updateNode(f.NewWithStatement(expression, statement), node.AsNode(), f.hooks) } return node.AsNode() } func (node *WithStatement) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) || visit(v, node.Statement) + return visit(v, node.Expression()) || visit(v, node.Statement()) } func (node *WithStatement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateWithStatement(node, v.visitNode(node.Expression), v.visitEmbeddedStatement(node.Statement)) + return v.Factory.UpdateWithStatement(node, v.visitNode(node.Expression()), v.visitEmbeddedStatement(node.Statement())) } func (node *WithStatement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewWithStatement(node.Expression, node.Statement), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewWithStatement(node.Expression(), node.Statement()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *WithStatement) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | - propagateSubtreeFacts(node.Statement) + return propagateSubtreeFacts(node.Expression()) | + propagateSubtreeFacts(node.Statement()) } func IsWithStatement(node *Node) bool { @@ -1228,39 +1362,47 @@ func IsWithStatement(node *Node) bool { type SwitchStatement struct { StatementBase CompositeBase - Expression *Expression - CaseBlock *CaseBlockNode + expression link[Node] // *Expression + caseBlock link[Node] // *CaseBlockNode } +func (node *SwitchStatement) Expression() *Expression { return node.expression.get() } + +func (node *SwitchStatement) SetExpression(expression *Expression) { node.expression.set(expression) } + +func (node *SwitchStatement) CaseBlock() *CaseBlockNode { return node.caseBlock.get() } + +func (node *SwitchStatement) SetCaseBlock(caseBlock *CaseBlockNode) { node.caseBlock.set(caseBlock) } + func (f *NodeFactory) NewSwitchStatement(expression *Expression, caseBlock *CaseBlockNode) *Node { - data := &SwitchStatement{} - data.Expression = expression - data.CaseBlock = caseBlock + data := newData[SwitchStatement](f) + data.expression.set(expression) + data.caseBlock.set(caseBlock) return f.newNode(KindSwitchStatement, data) } func (f *NodeFactory) UpdateSwitchStatement(node *SwitchStatement, expression *Expression, caseBlock *CaseBlockNode) *Node { - if expression != node.Expression || caseBlock != node.CaseBlock { + if expression != node.Expression() || caseBlock != node.CaseBlock() { return updateNode(f.NewSwitchStatement(expression, caseBlock), node.AsNode(), f.hooks) } return node.AsNode() } func (node *SwitchStatement) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) || visit(v, node.CaseBlock) + return visit(v, node.Expression()) || visit(v, node.CaseBlock()) } func (node *SwitchStatement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateSwitchStatement(node, v.visitNode(node.Expression), v.visitNode(node.CaseBlock)) + return v.Factory.UpdateSwitchStatement(node, v.visitNode(node.Expression()), v.visitNode(node.CaseBlock())) } func (node *SwitchStatement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewSwitchStatement(node.Expression, node.CaseBlock), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewSwitchStatement(node.Expression(), node.CaseBlock()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *SwitchStatement) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | - propagateSubtreeFacts(node.CaseBlock) + return propagateSubtreeFacts(node.Expression()) | + propagateSubtreeFacts(node.CaseBlock()) } func IsSwitchStatement(node *Node) bool { @@ -1275,36 +1417,40 @@ type CaseBlock struct { NodeBase LocalsContainerBase CompositeBase - Clauses *CaseClausesList + clauses link[NodeList] // *CaseClausesList } +func (node *CaseBlock) Clauses() *CaseClausesList { return node.clauses.get() } + +func (node *CaseBlock) SetClauses(clauses *CaseClausesList) { node.clauses.set(clauses) } + func (f *NodeFactory) NewCaseBlock(clauses *CaseClausesList) *Node { - data := &CaseBlock{} - data.Clauses = clauses + data := newData[CaseBlock](f) + data.clauses.set(clauses) return f.newNode(KindCaseBlock, data) } func (f *NodeFactory) UpdateCaseBlock(node *CaseBlock, clauses *CaseClausesList) *Node { - if clauses != node.Clauses { + if clauses != node.Clauses() { return updateNode(f.NewCaseBlock(clauses), node.AsNode(), f.hooks) } return node.AsNode() } func (node *CaseBlock) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.Clauses) + return visitNodeList(v, node.Clauses()) } func (node *CaseBlock) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateCaseBlock(node, v.visitNodes(node.Clauses)) + return v.Factory.UpdateCaseBlock(node, v.visitNodes(node.Clauses())) } func (node *CaseBlock) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewCaseBlock(node.Clauses), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewCaseBlock(node.Clauses()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *CaseBlock) computeSubtreeFacts() SubtreeFacts { - return propagateNodeListSubtreeFacts(node.Clauses, propagateSubtreeFacts) + return propagateNodeListSubtreeFacts(node.Clauses(), propagateSubtreeFacts) } func IsCaseBlock(node *Node) bool { @@ -1318,40 +1464,52 @@ func IsCaseBlock(node *Node) bool { type CaseOrDefaultClause struct { NodeBase CompositeBase - Expression *Expression - Statements *StatementList + expression link[Node] // *Expression + statements link[NodeList] // *StatementList FallthroughFlowNode *FlowNode } +func (node *CaseOrDefaultClause) Expression() *Expression { return node.expression.get() } + +func (node *CaseOrDefaultClause) SetExpression(expression *Expression) { + node.expression.set(expression) +} + +func (node *CaseOrDefaultClause) Statements() *StatementList { return node.statements.get() } + +func (node *CaseOrDefaultClause) SetStatements(statements *StatementList) { + node.statements.set(statements) +} + func (f *NodeFactory) NewCaseOrDefaultClause(kind Kind, expression *Expression, statements *StatementList) *Node { - data := &CaseOrDefaultClause{} - data.Expression = expression - data.Statements = statements + data := newData[CaseOrDefaultClause](f) + data.expression.set(expression) + data.statements.set(statements) return f.newNode(kind, data) } func (f *NodeFactory) UpdateCaseOrDefaultClause(node *CaseOrDefaultClause, expression *Expression, statements *StatementList) *Node { - if expression != node.Expression || statements != node.Statements { + if expression != node.Expression() || statements != node.Statements() { return updateNode(f.NewCaseOrDefaultClause(node.Kind, expression, statements), node.AsNode(), f.hooks) } return node.AsNode() } func (node *CaseOrDefaultClause) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) || visitNodeList(v, node.Statements) + return visit(v, node.Expression()) || visitNodeList(v, node.Statements()) } func (node *CaseOrDefaultClause) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateCaseOrDefaultClause(node, v.visitNode(node.Expression), v.visitNodes(node.Statements)) + return v.Factory.UpdateCaseOrDefaultClause(node, v.visitNode(node.Expression()), v.visitNodes(node.Statements())) } func (node *CaseOrDefaultClause) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewCaseOrDefaultClause(node.Kind, node.Expression, node.Statements), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewCaseOrDefaultClause(node.Kind, node.Expression(), node.Statements()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *CaseOrDefaultClause) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | - propagateNodeListSubtreeFacts(node.Statements, propagateSubtreeFacts) + return propagateSubtreeFacts(node.Expression()) | + propagateNodeListSubtreeFacts(node.Statements(), propagateSubtreeFacts) } func IsCaseClause(node *Node) bool { @@ -1369,36 +1527,40 @@ func IsDefaultClause(node *Node) bool { type ThrowStatement struct { StatementBase CompositeBase - Expression *Expression + expression link[Node] // *Expression } +func (node *ThrowStatement) Expression() *Expression { return node.expression.get() } + +func (node *ThrowStatement) SetExpression(expression *Expression) { node.expression.set(expression) } + func (f *NodeFactory) NewThrowStatement(expression *Expression) *Node { - data := &ThrowStatement{} - data.Expression = expression + data := newData[ThrowStatement](f) + data.expression.set(expression) return f.newNode(KindThrowStatement, data) } func (f *NodeFactory) UpdateThrowStatement(node *ThrowStatement, expression *Expression) *Node { - if expression != node.Expression { + if expression != node.Expression() { return updateNode(f.NewThrowStatement(expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ThrowStatement) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) + return visit(v, node.Expression()) } func (node *ThrowStatement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateThrowStatement(node, v.visitNode(node.Expression)) + return v.Factory.UpdateThrowStatement(node, v.visitNode(node.Expression())) } func (node *ThrowStatement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewThrowStatement(node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewThrowStatement(node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ThrowStatement) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) + return propagateSubtreeFacts(node.Expression()) } func IsThrowStatement(node *Node) bool { @@ -1412,42 +1574,58 @@ func IsThrowStatement(node *Node) bool { type TryStatement struct { StatementBase CompositeBase - TryBlock *BlockNode - CatchClause *CatchClauseNode // Optional - FinallyBlock *BlockNode // Optional + tryBlock link[Node] // *BlockNode + catchClause link[Node] // *CatchClauseNode. Optional + finallyBlock link[Node] // *BlockNode. Optional +} + +func (node *TryStatement) TryBlock() *BlockNode { return node.tryBlock.get() } + +func (node *TryStatement) SetTryBlock(tryBlock *BlockNode) { node.tryBlock.set(tryBlock) } + +func (node *TryStatement) CatchClause() *CatchClauseNode { return node.catchClause.get() } + +func (node *TryStatement) SetCatchClause(catchClause *CatchClauseNode) { + node.catchClause.set(catchClause) +} + +func (node *TryStatement) FinallyBlock() *BlockNode { return node.finallyBlock.get() } + +func (node *TryStatement) SetFinallyBlock(finallyBlock *BlockNode) { + node.finallyBlock.set(finallyBlock) } func (f *NodeFactory) NewTryStatement(tryBlock *BlockNode, catchClause *CatchClauseNode, finallyBlock *BlockNode) *Node { - data := &TryStatement{} - data.TryBlock = tryBlock - data.CatchClause = catchClause - data.FinallyBlock = finallyBlock + data := newData[TryStatement](f) + data.tryBlock.set(tryBlock) + data.catchClause.set(catchClause) + data.finallyBlock.set(finallyBlock) return f.newNode(KindTryStatement, data) } func (f *NodeFactory) UpdateTryStatement(node *TryStatement, tryBlock *BlockNode, catchClause *CatchClauseNode, finallyBlock *BlockNode) *Node { - if tryBlock != node.TryBlock || catchClause != node.CatchClause || finallyBlock != node.FinallyBlock { + if tryBlock != node.TryBlock() || catchClause != node.CatchClause() || finallyBlock != node.FinallyBlock() { return updateNode(f.NewTryStatement(tryBlock, catchClause, finallyBlock), node.AsNode(), f.hooks) } return node.AsNode() } func (node *TryStatement) ForEachChild(v Visitor) bool { - return visit(v, node.TryBlock) || visit(v, node.CatchClause) || visit(v, node.FinallyBlock) + return visit(v, node.TryBlock()) || visit(v, node.CatchClause()) || visit(v, node.FinallyBlock()) } func (node *TryStatement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateTryStatement(node, v.visitNode(node.TryBlock), v.visitNode(node.CatchClause), v.visitNode(node.FinallyBlock)) + return v.Factory.UpdateTryStatement(node, v.visitNode(node.TryBlock()), v.visitNode(node.CatchClause()), v.visitNode(node.FinallyBlock())) } func (node *TryStatement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewTryStatement(node.TryBlock, node.CatchClause, node.FinallyBlock), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewTryStatement(node.TryBlock(), node.CatchClause(), node.FinallyBlock()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *TryStatement) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.TryBlock) | - propagateSubtreeFacts(node.CatchClause) | - propagateSubtreeFacts(node.FinallyBlock) + return propagateSubtreeFacts(node.TryBlock()) | + propagateSubtreeFacts(node.CatchClause()) | + propagateSubtreeFacts(node.FinallyBlock()) } func IsTryStatement(node *Node) bool { @@ -1462,34 +1640,46 @@ type CatchClause struct { NodeBase LocalsContainerBase CompositeBase - VariableDeclaration *VariableDeclarationNode // Optional - Block *BlockNode + variableDeclaration link[Node] // *VariableDeclarationNode. Optional + block link[Node] // *BlockNode +} + +func (node *CatchClause) VariableDeclaration() *VariableDeclarationNode { + return node.variableDeclaration.get() } +func (node *CatchClause) SetVariableDeclaration(variableDeclaration *VariableDeclarationNode) { + node.variableDeclaration.set(variableDeclaration) +} + +func (node *CatchClause) Block() *BlockNode { return node.block.get() } + +func (node *CatchClause) SetBlock(block *BlockNode) { node.block.set(block) } + func (f *NodeFactory) NewCatchClause(variableDeclaration *VariableDeclarationNode, block *BlockNode) *Node { - data := &CatchClause{} - data.VariableDeclaration = variableDeclaration - data.Block = block + data := newData[CatchClause](f) + data.variableDeclaration.set(variableDeclaration) + data.block.set(block) return f.newNode(KindCatchClause, data) } func (f *NodeFactory) UpdateCatchClause(node *CatchClause, variableDeclaration *VariableDeclarationNode, block *BlockNode) *Node { - if variableDeclaration != node.VariableDeclaration || block != node.Block { + if variableDeclaration != node.VariableDeclaration() || block != node.Block() { return updateNode(f.NewCatchClause(variableDeclaration, block), node.AsNode(), f.hooks) } return node.AsNode() } func (node *CatchClause) ForEachChild(v Visitor) bool { - return visit(v, node.VariableDeclaration) || visit(v, node.Block) + return visit(v, node.VariableDeclaration()) || visit(v, node.Block()) } func (node *CatchClause) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateCatchClause(node, v.visitNode(node.VariableDeclaration), v.visitNode(node.Block)) + return v.Factory.UpdateCatchClause(node, v.visitNode(node.VariableDeclaration()), v.visitNode(node.Block())) } func (node *CatchClause) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewCatchClause(node.VariableDeclaration, node.Block), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewCatchClause(node.VariableDeclaration(), node.Block()), node.AsNode(), f.AsNodeFactory().hooks) } func IsCatchClause(node *Node) bool { @@ -1505,7 +1695,7 @@ type DebuggerStatement struct { } func (f *NodeFactory) NewDebuggerStatement() *Node { - data := &DebuggerStatement{} + data := newData[DebuggerStatement](f) return f.newNode(KindDebuggerStatement, data) } @@ -1523,39 +1713,47 @@ func IsDebuggerStatement(node *Node) bool { type LabeledStatement struct { StatementBase - Label *IdentifierNode - Statement *Statement + label link[Node] // *IdentifierNode + statement link[Node] // *Statement } +func (node *LabeledStatement) Label() *IdentifierNode { return node.label.get() } + +func (node *LabeledStatement) SetLabel(label *IdentifierNode) { node.label.set(label) } + +func (node *LabeledStatement) Statement() *Statement { return node.statement.get() } + +func (node *LabeledStatement) SetStatement(statement *Statement) { node.statement.set(statement) } + func (f *NodeFactory) NewLabeledStatement(label *IdentifierNode, statement *Statement) *Node { - data := &LabeledStatement{} - data.Label = label - data.Statement = statement + data := newData[LabeledStatement](f) + data.label.set(label) + data.statement.set(statement) return f.newNode(KindLabeledStatement, data) } func (f *NodeFactory) UpdateLabeledStatement(node *LabeledStatement, label *IdentifierNode, statement *Statement) *Node { - if label != node.Label || statement != node.Statement { + if label != node.Label() || statement != node.Statement() { return updateNode(f.NewLabeledStatement(label, statement), node.AsNode(), f.hooks) } return node.AsNode() } func (node *LabeledStatement) ForEachChild(v Visitor) bool { - return visit(v, node.Label) || visit(v, node.Statement) + return visit(v, node.Label()) || visit(v, node.Statement()) } func (node *LabeledStatement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateLabeledStatement(node, v.visitNode(node.Label), v.visitEmbeddedStatement(node.Statement)) + return v.Factory.UpdateLabeledStatement(node, v.visitNode(node.Label()), v.visitEmbeddedStatement(node.Statement())) } func (node *LabeledStatement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewLabeledStatement(node.Label, node.Statement), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewLabeledStatement(node.Label(), node.Statement()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *LabeledStatement) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Label) | - propagateSubtreeFacts(node.Statement) + return propagateSubtreeFacts(node.Label()) | + propagateSubtreeFacts(node.Statement()) } func IsLabeledStatement(node *Node) bool { @@ -1568,36 +1766,42 @@ func IsLabeledStatement(node *Node) bool { type ExpressionStatement struct { StatementBase - Expression *Expression + expression link[Node] // *Expression +} + +func (node *ExpressionStatement) Expression() *Expression { return node.expression.get() } + +func (node *ExpressionStatement) SetExpression(expression *Expression) { + node.expression.set(expression) } func (f *NodeFactory) NewExpressionStatement(expression *Expression) *Node { - data := f.expressionStatementArena.New() - data.Expression = expression + data := newData[ExpressionStatement](f) + data.expression.set(expression) return f.newNode(KindExpressionStatement, data) } func (f *NodeFactory) UpdateExpressionStatement(node *ExpressionStatement, expression *Expression) *Node { - if expression != node.Expression { + if expression != node.Expression() { return updateNode(f.NewExpressionStatement(expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ExpressionStatement) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) + return visit(v, node.Expression()) } func (node *ExpressionStatement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateExpressionStatement(node, v.visitNode(node.Expression)) + return v.Factory.UpdateExpressionStatement(node, v.visitNode(node.Expression())) } func (node *ExpressionStatement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewExpressionStatement(node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewExpressionStatement(node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ExpressionStatement) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) + return propagateSubtreeFacts(node.Expression()) } func IsExpressionStatement(node *Node) bool { @@ -1612,38 +1816,42 @@ type Block struct { StatementBase LocalsContainerBase CompositeBase - Statements *StatementList + statements link[NodeList] // *StatementList MultiLine bool } +func (node *Block) Statements() *StatementList { return node.statements.get() } + +func (node *Block) SetStatements(statements *StatementList) { node.statements.set(statements) } + func (f *NodeFactory) NewBlock(statements *StatementList, multiLine bool) *Node { - data := f.blockArena.New() - data.Statements = statements + data := newData[Block](f) + data.statements.set(statements) data.MultiLine = multiLine return f.newNode(KindBlock, data) } func (f *NodeFactory) UpdateBlock(node *Block, statements *StatementList, multiLine bool) *Node { - if statements != node.Statements || multiLine != node.MultiLine { + if statements != node.Statements() || multiLine != node.MultiLine { return updateNode(f.NewBlock(statements, multiLine), node.AsNode(), f.hooks) } return node.AsNode() } func (node *Block) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.Statements) + return visitNodeList(v, node.Statements()) } func (node *Block) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateBlock(node, v.visitNodes(node.Statements), node.MultiLine) + return v.Factory.UpdateBlock(node, v.visitNodes(node.Statements()), node.MultiLine) } func (node *Block) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewBlock(node.Statements, node.MultiLine), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewBlock(node.Statements(), node.MultiLine), node.AsNode(), f.AsNodeFactory().hooks) } func (node *Block) computeSubtreeFacts() SubtreeFacts { - return propagateNodeListSubtreeFacts(node.Statements, propagateSubtreeFacts) + return propagateNodeListSubtreeFacts(node.Statements(), propagateSubtreeFacts) } func IsBlock(node *Node) bool { @@ -1658,33 +1866,41 @@ type VariableStatement struct { StatementBase ModifiersBase CompositeBase - DeclarationList *VariableDeclarationListNode + declarationList link[Node] // *VariableDeclarationListNode +} + +func (node *VariableStatement) DeclarationList() *VariableDeclarationListNode { + return node.declarationList.get() +} + +func (node *VariableStatement) SetDeclarationList(declarationList *VariableDeclarationListNode) { + node.declarationList.set(declarationList) } func (f *NodeFactory) NewVariableStatement(modifiers *ModifierList, declarationList *VariableDeclarationListNode) *Node { - data := f.variableStatementArena.New() - data.modifiers = modifiers - data.DeclarationList = declarationList + data := newData[VariableStatement](f) + data.modifiers.set(modifiers) + data.declarationList.set(declarationList) return f.newNode(KindVariableStatement, data) } func (f *NodeFactory) UpdateVariableStatement(node *VariableStatement, modifiers *ModifierList, declarationList *VariableDeclarationListNode) *Node { - if modifiers != node.modifiers || declarationList != node.DeclarationList { + if modifiers != node.modifiers.get() || declarationList != node.DeclarationList() { return updateNode(f.NewVariableStatement(modifiers, declarationList), node.AsNode(), f.hooks) } return node.AsNode() } func (node *VariableStatement) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || visit(v, node.DeclarationList) + return visitModifiers(v, node.modifiers.get()) || visit(v, node.DeclarationList()) } func (node *VariableStatement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateVariableStatement(node, v.visitModifiers(node.modifiers), v.visitNode(node.DeclarationList)) + return v.Factory.UpdateVariableStatement(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.DeclarationList())) } func (node *VariableStatement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewVariableStatement(node.Modifiers(), node.DeclarationList), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewVariableStatement(node.Modifiers(), node.DeclarationList()), node.AsNode(), f.AsNodeFactory().hooks) } func IsVariableStatement(node *Node) bool { @@ -1700,45 +1916,63 @@ type VariableDeclaration struct { DeclarationBase ExportableBase CompositeBase - name *BindingName - ExclamationToken *ExclamationToken // Optional - Type *TypeNode // Optional - Initializer *Expression // Optional + name link[Node] // *BindingName + exclamationToken link[Node] // *ExclamationToken. Optional + typeNode link[Node] // *TypeNode. Optional + initializer link[Node] // *Expression. Optional +} + +func (node *VariableDeclaration) ExclamationToken() *ExclamationToken { + return node.exclamationToken.get() +} + +func (node *VariableDeclaration) SetExclamationToken(exclamationToken *ExclamationToken) { + node.exclamationToken.set(exclamationToken) +} + +func (node *VariableDeclaration) Type() *TypeNode { return node.typeNode.get() } + +func (node *VariableDeclaration) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + +func (node *VariableDeclaration) Initializer() *Expression { return node.initializer.get() } + +func (node *VariableDeclaration) SetInitializer(initializer *Expression) { + node.initializer.set(initializer) } func (f *NodeFactory) NewVariableDeclaration(name *BindingName, exclamationToken *ExclamationToken, typeNode *TypeNode, initializer *Expression) *Node { - data := f.variableDeclarationArena.New() - data.name = name - data.ExclamationToken = exclamationToken - data.Type = typeNode - data.Initializer = initializer + data := newData[VariableDeclaration](f) + data.name.set(name) + data.exclamationToken.set(exclamationToken) + data.typeNode.set(typeNode) + data.initializer.set(initializer) return f.newNode(KindVariableDeclaration, data) } func (f *NodeFactory) UpdateVariableDeclaration(node *VariableDeclaration, name *BindingName, exclamationToken *ExclamationToken, typeNode *TypeNode, initializer *Expression) *Node { - if name != node.name || exclamationToken != node.ExclamationToken || typeNode != node.Type || initializer != node.Initializer { + if name != node.name.get() || exclamationToken != node.ExclamationToken() || typeNode != node.Type() || initializer != node.Initializer() { return updateNode(f.NewVariableDeclaration(name, exclamationToken, typeNode, initializer), node.AsNode(), f.hooks) } return node.AsNode() } func (node *VariableDeclaration) ForEachChild(v Visitor) bool { - return visit(v, node.name) || - visit(v, node.ExclamationToken) || - visit(v, node.Type) || - visit(v, node.Initializer) + return visit(v, node.name.get()) || + visit(v, node.ExclamationToken()) || + visit(v, node.Type()) || + visit(v, node.Initializer()) } func (node *VariableDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateVariableDeclaration(node, v.visitNode(node.name), v.visitNode(node.ExclamationToken), v.visitNode(node.Type), v.visitNode(node.Initializer)) + return v.Factory.UpdateVariableDeclaration(node, v.visitNode(node.name.get()), v.visitNode(node.ExclamationToken()), v.visitNode(node.Type()), v.visitNode(node.Initializer())) } func (node *VariableDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewVariableDeclaration(node.name, node.ExclamationToken, node.Type, node.Initializer), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewVariableDeclaration(node.name.get(), node.ExclamationToken(), node.Type(), node.Initializer()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *VariableDeclaration) Name() *DeclarationName { - return node.name + return node.name.get() } func IsVariableDeclaration(node *Node) bool { @@ -1752,34 +1986,42 @@ func IsVariableDeclaration(node *Node) bool { type VariableDeclarationList struct { NodeBase CompositeBase - Declarations *VariableDeclarationNodeList + declarations link[NodeList] // *VariableDeclarationNodeList +} + +func (node *VariableDeclarationList) Declarations() *VariableDeclarationNodeList { + return node.declarations.get() +} + +func (node *VariableDeclarationList) SetDeclarations(declarations *VariableDeclarationNodeList) { + node.declarations.set(declarations) } func (f *NodeFactory) NewVariableDeclarationList(declarations *VariableDeclarationNodeList, flags NodeFlags) *Node { - data := f.variableDeclarationListArena.New() - data.Declarations = declarations + data := newData[VariableDeclarationList](f) + data.declarations.set(declarations) node := f.newNode(KindVariableDeclarationList, data) node.Flags = flags return node } func (f *NodeFactory) UpdateVariableDeclarationList(node *VariableDeclarationList, declarations *VariableDeclarationNodeList, flags NodeFlags) *Node { - if declarations != node.Declarations || flags != node.Flags { + if declarations != node.Declarations() || flags != node.Flags { return updateNode(f.NewVariableDeclarationList(declarations, flags), node.AsNode(), f.hooks) } return node.AsNode() } func (node *VariableDeclarationList) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.Declarations) + return visitNodeList(v, node.Declarations()) } func (node *VariableDeclarationList) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateVariableDeclarationList(node, v.visitNodes(node.Declarations), node.Flags) + return v.Factory.UpdateVariableDeclarationList(node, v.visitNodes(node.Declarations()), node.Flags) } func (node *VariableDeclarationList) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewVariableDeclarationList(node.Declarations, node.Flags), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewVariableDeclarationList(node.Declarations(), node.Flags), node.AsNode(), f.AsNodeFactory().hooks) } func IsVariableDeclarationList(node *Node) bool { @@ -1793,32 +2035,36 @@ func IsVariableDeclarationList(node *Node) bool { type BindingPattern struct { NodeBase CompositeBase - Elements *BindingElementList + elements link[NodeList] // *BindingElementList } +func (node *BindingPattern) Elements() *BindingElementList { return node.elements.get() } + +func (node *BindingPattern) SetElements(elements *BindingElementList) { node.elements.set(elements) } + func (f *NodeFactory) NewBindingPattern(kind Kind, elements *BindingElementList) *Node { - data := &BindingPattern{} - data.Elements = elements + data := newData[BindingPattern](f) + data.elements.set(elements) return f.newNode(kind, data) } func (f *NodeFactory) UpdateBindingPattern(node *BindingPattern, elements *BindingElementList) *Node { - if elements != node.Elements { + if elements != node.Elements() { return updateNode(f.NewBindingPattern(node.Kind, elements), node.AsNode(), f.hooks) } return node.AsNode() } func (node *BindingPattern) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.Elements) + return visitNodeList(v, node.Elements()) } func (node *BindingPattern) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateBindingPattern(node, v.visitNodes(node.Elements)) + return v.Factory.UpdateBindingPattern(node, v.visitNodes(node.Elements())) } func (node *BindingPattern) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewBindingPattern(node.Kind, node.Elements), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewBindingPattern(node.Kind, node.Elements()), node.AsNode(), f.AsNodeFactory().hooks) } func IsObjectBindingPattern(node *Node) bool { @@ -1838,50 +2084,72 @@ type ParameterDeclaration struct { DeclarationBase ModifiersBase CompositeBase - DotDotDotToken *DotDotDotToken // Optional - name *BindingName - QuestionToken *QuestionToken // Optional - Type *TypeNode // Optional - Initializer *Expression // Optional + dotDotDotToken link[Node] // *DotDotDotToken. Optional + name link[Node] // *BindingName + questionToken link[Node] // *QuestionToken. Optional + typeNode link[Node] // *TypeNode. Optional + initializer link[Node] // *Expression. Optional +} + +func (node *ParameterDeclaration) DotDotDotToken() *DotDotDotToken { return node.dotDotDotToken.get() } + +func (node *ParameterDeclaration) SetDotDotDotToken(dotDotDotToken *DotDotDotToken) { + node.dotDotDotToken.set(dotDotDotToken) +} + +func (node *ParameterDeclaration) QuestionToken() *QuestionToken { return node.questionToken.get() } + +func (node *ParameterDeclaration) SetQuestionToken(questionToken *QuestionToken) { + node.questionToken.set(questionToken) +} + +func (node *ParameterDeclaration) Type() *TypeNode { return node.typeNode.get() } + +func (node *ParameterDeclaration) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + +func (node *ParameterDeclaration) Initializer() *Expression { return node.initializer.get() } + +func (node *ParameterDeclaration) SetInitializer(initializer *Expression) { + node.initializer.set(initializer) } func (f *NodeFactory) NewParameterDeclaration(modifiers *ModifierList, dotDotDotToken *DotDotDotToken, name *BindingName, questionToken *QuestionToken, typeNode *TypeNode, initializer *Expression) *Node { - data := f.parameterDeclarationArena.New() - data.modifiers = modifiers - data.DotDotDotToken = dotDotDotToken - data.name = name - data.QuestionToken = questionToken - data.Type = typeNode - data.Initializer = initializer + data := newData[ParameterDeclaration](f) + data.modifiers.set(modifiers) + data.dotDotDotToken.set(dotDotDotToken) + data.name.set(name) + data.questionToken.set(questionToken) + data.typeNode.set(typeNode) + data.initializer.set(initializer) return f.newNode(KindParameter, data) } func (f *NodeFactory) UpdateParameterDeclaration(node *ParameterDeclaration, modifiers *ModifierList, dotDotDotToken *DotDotDotToken, name *BindingName, questionToken *QuestionToken, typeNode *TypeNode, initializer *Expression) *Node { - if modifiers != node.modifiers || dotDotDotToken != node.DotDotDotToken || name != node.name || questionToken != node.QuestionToken || typeNode != node.Type || initializer != node.Initializer { + if modifiers != node.modifiers.get() || dotDotDotToken != node.DotDotDotToken() || name != node.name.get() || questionToken != node.QuestionToken() || typeNode != node.Type() || initializer != node.Initializer() { return updateNode(f.NewParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, typeNode, initializer), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ParameterDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.DotDotDotToken) || - visit(v, node.name) || - visit(v, node.QuestionToken) || - visit(v, node.Type) || - visit(v, node.Initializer) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.DotDotDotToken()) || + visit(v, node.name.get()) || + visit(v, node.QuestionToken()) || + visit(v, node.Type()) || + visit(v, node.Initializer()) } func (node *ParameterDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateParameterDeclaration(node, v.visitModifiers(node.modifiers), v.visitNode(node.DotDotDotToken), v.visitNode(node.name), v.visitNode(node.QuestionToken), v.visitNode(node.Type), v.visitNode(node.Initializer)) + return v.Factory.UpdateParameterDeclaration(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.DotDotDotToken()), v.visitNode(node.name.get()), v.visitNode(node.QuestionToken()), v.visitNode(node.Type()), v.visitNode(node.Initializer())) } func (node *ParameterDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewParameterDeclaration(node.Modifiers(), node.DotDotDotToken, node.name, node.QuestionToken, node.Type, node.Initializer), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewParameterDeclaration(node.Modifiers(), node.DotDotDotToken(), node.name.get(), node.QuestionToken(), node.Type(), node.Initializer()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ParameterDeclaration) Name() *DeclarationName { - return node.name + return node.name.get() } func IsParameterDeclaration(node *Node) bool { @@ -1898,45 +2166,63 @@ type BindingElement struct { ExportableBase FlowNodeBase CompositeBase - DotDotDotToken *DotDotDotToken // Optional - PropertyName *PropertyName // Optional - name *BindingName // Optional - Initializer *Expression // Optional + dotDotDotToken link[Node] // *DotDotDotToken. Optional + propertyName link[Node] // *PropertyName. Optional + name link[Node] // *BindingName. Optional + initializer link[Node] // *Expression. Optional +} + +func (node *BindingElement) DotDotDotToken() *DotDotDotToken { return node.dotDotDotToken.get() } + +func (node *BindingElement) SetDotDotDotToken(dotDotDotToken *DotDotDotToken) { + node.dotDotDotToken.set(dotDotDotToken) +} + +func (node *BindingElement) PropertyName() *PropertyName { return node.propertyName.get() } + +func (node *BindingElement) SetPropertyName(propertyName *PropertyName) { + node.propertyName.set(propertyName) +} + +func (node *BindingElement) Initializer() *Expression { return node.initializer.get() } + +func (node *BindingElement) SetInitializer(initializer *Expression) { + node.initializer.set(initializer) } func (f *NodeFactory) NewBindingElement(dotDotDotToken *DotDotDotToken, propertyName *PropertyName, name *BindingName, initializer *Expression) *Node { - data := &BindingElement{} - data.DotDotDotToken = dotDotDotToken - data.PropertyName = propertyName - data.name = name - data.Initializer = initializer + data := newData[BindingElement](f) + data.dotDotDotToken.set(dotDotDotToken) + data.propertyName.set(propertyName) + data.name.set(name) + data.initializer.set(initializer) return f.newNode(KindBindingElement, data) } func (f *NodeFactory) UpdateBindingElement(node *BindingElement, dotDotDotToken *DotDotDotToken, propertyName *PropertyName, name *BindingName, initializer *Expression) *Node { - if dotDotDotToken != node.DotDotDotToken || propertyName != node.PropertyName || name != node.name || initializer != node.Initializer { + if dotDotDotToken != node.DotDotDotToken() || propertyName != node.PropertyName() || name != node.name.get() || initializer != node.Initializer() { return updateNode(f.NewBindingElement(dotDotDotToken, propertyName, name, initializer), node.AsNode(), f.hooks) } return node.AsNode() } func (node *BindingElement) ForEachChild(v Visitor) bool { - return visit(v, node.DotDotDotToken) || - visit(v, node.PropertyName) || - visit(v, node.name) || - visit(v, node.Initializer) + return visit(v, node.DotDotDotToken()) || + visit(v, node.PropertyName()) || + visit(v, node.name.get()) || + visit(v, node.Initializer()) } func (node *BindingElement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateBindingElement(node, v.visitNode(node.DotDotDotToken), v.visitNode(node.PropertyName), v.visitNode(node.name), v.visitNode(node.Initializer)) + return v.Factory.UpdateBindingElement(node, v.visitNode(node.DotDotDotToken()), v.visitNode(node.PropertyName()), v.visitNode(node.name.get()), v.visitNode(node.Initializer())) } func (node *BindingElement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewBindingElement(node.DotDotDotToken, node.PropertyName, node.name, node.Initializer), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewBindingElement(node.DotDotDotToken(), node.PropertyName(), node.name.get(), node.Initializer()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *BindingElement) Name() *DeclarationName { - return node.name + return node.name.get() } func IsBindingElement(node *Node) bool { @@ -1954,24 +2240,24 @@ type MissingDeclaration struct { } func (f *NodeFactory) NewMissingDeclaration(modifiers *ModifierList) *Node { - data := &MissingDeclaration{} - data.modifiers = modifiers + data := newData[MissingDeclaration](f) + data.modifiers.set(modifiers) return f.newNode(KindMissingDeclaration, data) } func (f *NodeFactory) UpdateMissingDeclaration(node *MissingDeclaration, modifiers *ModifierList) *Node { - if modifiers != node.modifiers { + if modifiers != node.modifiers.get() { return updateNode(f.NewMissingDeclaration(modifiers), node.AsNode(), f.hooks) } return node.AsNode() } func (node *MissingDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) + return visitModifiers(v, node.modifiers.get()) } func (node *MissingDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateMissingDeclaration(node, v.visitModifiers(node.modifiers)) + return v.Factory.UpdateMissingDeclaration(node, v.visitModifiers(node.modifiers.get())) } func (node *MissingDeclaration) Clone(f NodeFactoryCoercible) *Node { @@ -1993,51 +2279,51 @@ type FunctionDeclaration struct { ModifiersBase FunctionLikeWithBodyBase CompositeBase - name *IdentifierNode // Optional + name link[Node] // *IdentifierNode. Optional ReturnFlowNode *FlowNode } func (f *NodeFactory) NewFunctionDeclaration(modifiers *ModifierList, asteriskToken *AsteriskToken, name *IdentifierNode, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode, fullSignature *TypeNode, body *FunctionBody) *Node { - data := f.functionDeclarationArena.New() - data.modifiers = modifiers - data.AsteriskToken = asteriskToken - data.name = name - data.TypeParameters = typeParameters - data.Parameters = parameters - data.Type = typeNode - data.FullSignature = fullSignature - data.Body = body + data := newData[FunctionDeclaration](f) + data.modifiers.set(modifiers) + data.asteriskToken.set(asteriskToken) + data.name.set(name) + data.typeParameters.set(typeParameters) + data.parameters.set(parameters) + data.typeNode.set(typeNode) + data.fullSignature.set(fullSignature) + data.body.set(body) return f.newNode(KindFunctionDeclaration, data) } func (f *NodeFactory) UpdateFunctionDeclaration(node *FunctionDeclaration, modifiers *ModifierList, asteriskToken *AsteriskToken, name *IdentifierNode, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode, fullSignature *TypeNode, body *FunctionBody) *Node { - if modifiers != node.modifiers || asteriskToken != node.AsteriskToken || name != node.name || typeParameters != node.TypeParameters || parameters != node.Parameters || typeNode != node.Type || fullSignature != node.FullSignature || body != node.Body { + if modifiers != node.modifiers.get() || asteriskToken != node.AsteriskToken() || name != node.name.get() || typeParameters != node.TypeParameters() || parameters != node.Parameters() || typeNode != node.Type() || fullSignature != node.FullSignature() || body != node.Body() { return updateNode(f.NewFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, typeNode, fullSignature, body), node.AsNode(), f.hooks) } return node.AsNode() } func (node *FunctionDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.AsteriskToken) || - visit(v, node.name) || - visitNodeList(v, node.TypeParameters) || - visitNodeList(v, node.Parameters) || - visit(v, node.Type) || - visit(v, node.FullSignature) || - visit(v, node.Body) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.AsteriskToken()) || + visit(v, node.name.get()) || + visitNodeList(v, node.TypeParameters()) || + visitNodeList(v, node.Parameters()) || + visit(v, node.Type()) || + visit(v, node.FullSignature()) || + visit(v, node.Body()) } func (node *FunctionDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateFunctionDeclaration(node, v.visitModifiers(node.modifiers), v.visitNode(node.AsteriskToken), v.visitNode(node.name), v.visitNodes(node.TypeParameters), v.visitParameters(node.Parameters), v.visitNode(node.Type), v.visitNode(node.FullSignature), v.visitFunctionBody(node.Body)) + return v.Factory.UpdateFunctionDeclaration(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.AsteriskToken()), v.visitNode(node.name.get()), v.visitNodes(node.TypeParameters()), v.visitParameters(node.Parameters()), v.visitNode(node.Type()), v.visitNode(node.FullSignature()), v.visitFunctionBody(node.Body())) } func (node *FunctionDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewFunctionDeclaration(node.Modifiers(), node.AsteriskToken, node.name, node.TypeParameters, node.Parameters, node.Type, node.FullSignature, node.Body), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewFunctionDeclaration(node.Modifiers(), node.AsteriskToken(), node.name.get(), node.TypeParameters(), node.Parameters(), node.Type(), node.FullSignature(), node.Body()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *FunctionDeclaration) Name() *DeclarationName { - return node.name + return node.name.get() } func IsFunctionDeclaration(node *Node) bool { @@ -2055,40 +2341,40 @@ type ClassDeclaration struct { } func (f *NodeFactory) NewClassDeclaration(modifiers *ModifierList, name *IdentifierNode, typeParameters *TypeParameterList, heritageClauses *HeritageClauseList, members *ClassElementList) *Node { - data := &ClassDeclaration{} - data.modifiers = modifiers - data.name = name - data.TypeParameters = typeParameters - data.HeritageClauses = heritageClauses - data.Members = members + data := newData[ClassDeclaration](f) + data.modifiers.set(modifiers) + data.name.set(name) + data.typeParameters.set(typeParameters) + data.heritageClauses.set(heritageClauses) + data.members.set(members) return f.newNode(KindClassDeclaration, data) } func (f *NodeFactory) UpdateClassDeclaration(node *ClassDeclaration, modifiers *ModifierList, name *IdentifierNode, typeParameters *TypeParameterList, heritageClauses *HeritageClauseList, members *ClassElementList) *Node { - if modifiers != node.modifiers || name != node.name || typeParameters != node.TypeParameters || heritageClauses != node.HeritageClauses || members != node.Members { + if modifiers != node.modifiers.get() || name != node.name.get() || typeParameters != node.TypeParameters() || heritageClauses != node.HeritageClauses() || members != node.Members() { return updateNode(f.NewClassDeclaration(modifiers, name, typeParameters, heritageClauses, members), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ClassDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.name) || - visitNodeList(v, node.TypeParameters) || - visitNodeList(v, node.HeritageClauses) || - visitNodeList(v, node.Members) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.name.get()) || + visitNodeList(v, node.TypeParameters()) || + visitNodeList(v, node.HeritageClauses()) || + visitNodeList(v, node.Members()) } func (node *ClassDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateClassDeclaration(node, v.visitModifiers(node.modifiers), v.visitNode(node.name), v.visitNodes(node.TypeParameters), v.visitNodes(node.HeritageClauses), v.visitNodes(node.Members)) + return v.Factory.UpdateClassDeclaration(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.name.get()), v.visitNodes(node.TypeParameters()), v.visitNodes(node.HeritageClauses()), v.visitNodes(node.Members())) } func (node *ClassDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewClassDeclaration(node.Modifiers(), node.name, node.TypeParameters, node.HeritageClauses, node.Members), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewClassDeclaration(node.Modifiers(), node.name.get(), node.TypeParameters(), node.HeritageClauses(), node.Members()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ClassDeclaration) Name() *DeclarationName { - return node.name + return node.name.get() } func IsClassDeclaration(node *Node) bool { @@ -2106,40 +2392,40 @@ type ClassExpression struct { } func (f *NodeFactory) NewClassExpression(modifiers *ModifierList, name *IdentifierNode, typeParameters *TypeParameterList, heritageClauses *HeritageClauseList, members *ClassElementList) *Node { - data := &ClassExpression{} - data.modifiers = modifiers - data.name = name - data.TypeParameters = typeParameters - data.HeritageClauses = heritageClauses - data.Members = members + data := newData[ClassExpression](f) + data.modifiers.set(modifiers) + data.name.set(name) + data.typeParameters.set(typeParameters) + data.heritageClauses.set(heritageClauses) + data.members.set(members) return f.newNode(KindClassExpression, data) } func (f *NodeFactory) UpdateClassExpression(node *ClassExpression, modifiers *ModifierList, name *IdentifierNode, typeParameters *TypeParameterList, heritageClauses *HeritageClauseList, members *ClassElementList) *Node { - if modifiers != node.modifiers || name != node.name || typeParameters != node.TypeParameters || heritageClauses != node.HeritageClauses || members != node.Members { + if modifiers != node.modifiers.get() || name != node.name.get() || typeParameters != node.TypeParameters() || heritageClauses != node.HeritageClauses() || members != node.Members() { return updateNode(f.NewClassExpression(modifiers, name, typeParameters, heritageClauses, members), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ClassExpression) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.name) || - visitNodeList(v, node.TypeParameters) || - visitNodeList(v, node.HeritageClauses) || - visitNodeList(v, node.Members) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.name.get()) || + visitNodeList(v, node.TypeParameters()) || + visitNodeList(v, node.HeritageClauses()) || + visitNodeList(v, node.Members()) } func (node *ClassExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateClassExpression(node, v.visitModifiers(node.modifiers), v.visitNode(node.name), v.visitNodes(node.TypeParameters), v.visitNodes(node.HeritageClauses), v.visitNodes(node.Members)) + return v.Factory.UpdateClassExpression(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.name.get()), v.visitNodes(node.TypeParameters()), v.visitNodes(node.HeritageClauses()), v.visitNodes(node.Members())) } func (node *ClassExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewClassExpression(node.Modifiers(), node.name, node.TypeParameters, node.HeritageClauses, node.Members), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewClassExpression(node.Modifiers(), node.name.get(), node.TypeParameters(), node.HeritageClauses(), node.Members()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ClassExpression) Name() *DeclarationName { - return node.name + return node.name.get() } func IsClassExpression(node *Node) bool { @@ -2154,33 +2440,37 @@ type HeritageClause struct { NodeBase CompositeBase Token Kind - Types *HeritageClauseElementList + types link[NodeList] // *HeritageClauseElementList } +func (node *HeritageClause) Types() *HeritageClauseElementList { return node.types.get() } + +func (node *HeritageClause) SetTypes(types *HeritageClauseElementList) { node.types.set(types) } + func (f *NodeFactory) NewHeritageClause(token Kind, types *HeritageClauseElementList) *Node { - data := f.heritageClauseArena.New() + data := newData[HeritageClause](f) data.Token = token - data.Types = types + data.types.set(types) return f.newNode(KindHeritageClause, data) } func (f *NodeFactory) UpdateHeritageClause(node *HeritageClause, token Kind, types *HeritageClauseElementList) *Node { - if token != node.Token || types != node.Types { + if token != node.Token || types != node.Types() { return updateNode(f.NewHeritageClause(token, types), node.AsNode(), f.hooks) } return node.AsNode() } func (node *HeritageClause) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.Types) + return visitNodeList(v, node.Types()) } func (node *HeritageClause) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateHeritageClause(node, node.Token, v.visitNodes(node.Types)) + return v.Factory.UpdateHeritageClause(node, node.Token, v.visitNodes(node.Types())) } func (node *HeritageClause) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewHeritageClause(node.Token, node.Types), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewHeritageClause(node.Token, node.Types()), node.AsNode(), f.AsNodeFactory().hooks) } func IsHeritageClause(node *Node) bool { @@ -2197,47 +2487,67 @@ type InterfaceDeclaration struct { DeclarationBase ExportableBase ModifiersBase - name *IdentifierNode - TypeParameters *TypeParameterList // Optional - HeritageClauses *HeritageClauseList // Optional - Members *TypeElementList + name link[Node] // *IdentifierNode + typeParameters link[NodeList] // *TypeParameterList. Optional + heritageClauses link[NodeList] // *HeritageClauseList. Optional + members link[NodeList] // *TypeElementList +} + +func (node *InterfaceDeclaration) TypeParameters() *TypeParameterList { + return node.typeParameters.get() +} + +func (node *InterfaceDeclaration) SetTypeParameters(typeParameters *TypeParameterList) { + node.typeParameters.set(typeParameters) +} + +func (node *InterfaceDeclaration) HeritageClauses() *HeritageClauseList { + return node.heritageClauses.get() +} + +func (node *InterfaceDeclaration) SetHeritageClauses(heritageClauses *HeritageClauseList) { + node.heritageClauses.set(heritageClauses) } +func (node *InterfaceDeclaration) Members() *TypeElementList { return node.members.get() } + +func (node *InterfaceDeclaration) SetMembers(members *TypeElementList) { node.members.set(members) } + func (f *NodeFactory) NewInterfaceDeclaration(modifiers *ModifierList, name *IdentifierNode, typeParameters *TypeParameterList, heritageClauses *HeritageClauseList, members *TypeElementList) *Node { - data := f.interfaceDeclarationArena.New() - data.modifiers = modifiers - data.name = name - data.TypeParameters = typeParameters - data.HeritageClauses = heritageClauses - data.Members = members + data := newData[InterfaceDeclaration](f) + data.modifiers.set(modifiers) + data.name.set(name) + data.typeParameters.set(typeParameters) + data.heritageClauses.set(heritageClauses) + data.members.set(members) return f.newNode(KindInterfaceDeclaration, data) } func (f *NodeFactory) UpdateInterfaceDeclaration(node *InterfaceDeclaration, modifiers *ModifierList, name *IdentifierNode, typeParameters *TypeParameterList, heritageClauses *HeritageClauseList, members *TypeElementList) *Node { - if modifiers != node.modifiers || name != node.name || typeParameters != node.TypeParameters || heritageClauses != node.HeritageClauses || members != node.Members { + if modifiers != node.modifiers.get() || name != node.name.get() || typeParameters != node.TypeParameters() || heritageClauses != node.HeritageClauses() || members != node.Members() { return updateNode(f.NewInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members), node.AsNode(), f.hooks) } return node.AsNode() } func (node *InterfaceDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.name) || - visitNodeList(v, node.TypeParameters) || - visitNodeList(v, node.HeritageClauses) || - visitNodeList(v, node.Members) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.name.get()) || + visitNodeList(v, node.TypeParameters()) || + visitNodeList(v, node.HeritageClauses()) || + visitNodeList(v, node.Members()) } func (node *InterfaceDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateInterfaceDeclaration(node, v.visitModifiers(node.modifiers), v.visitNode(node.name), v.visitNodes(node.TypeParameters), v.visitNodes(node.HeritageClauses), v.visitNodes(node.Members)) + return v.Factory.UpdateInterfaceDeclaration(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.name.get()), v.visitNodes(node.TypeParameters()), v.visitNodes(node.HeritageClauses()), v.visitNodes(node.Members())) } func (node *InterfaceDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewInterfaceDeclaration(node.Modifiers(), node.name, node.TypeParameters, node.HeritageClauses, node.Members), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewInterfaceDeclaration(node.Modifiers(), node.name.get(), node.TypeParameters(), node.HeritageClauses(), node.Members()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *InterfaceDeclaration) Name() *DeclarationName { - return node.name + return node.name.get() } func IsInterfaceDeclaration(node *Node) bool { @@ -2255,31 +2565,43 @@ type TypeAliasDeclaration struct { ExportableBase ModifiersBase LocalsContainerBase - name *IdentifierNode - TypeParameters *TypeParameterList // Optional - Type *TypeNode + name link[Node] // *IdentifierNode + typeParameters link[NodeList] // *TypeParameterList. Optional + typeNode link[Node] // *TypeNode +} + +func (node *TypeAliasDeclaration) TypeParameters() *TypeParameterList { + return node.typeParameters.get() +} + +func (node *TypeAliasDeclaration) SetTypeParameters(typeParameters *TypeParameterList) { + node.typeParameters.set(typeParameters) } +func (node *TypeAliasDeclaration) Type() *TypeNode { return node.typeNode.get() } + +func (node *TypeAliasDeclaration) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + func (f *NodeFactory) NewTypeAliasDeclaration(modifiers *ModifierList, name *IdentifierNode, typeParameters *TypeParameterList, typeNode *TypeNode) *Node { - data := f.typeAliasDeclarationArena.New() - data.modifiers = modifiers - data.name = name - data.TypeParameters = typeParameters - data.Type = typeNode + data := newData[TypeAliasDeclaration](f) + data.modifiers.set(modifiers) + data.name.set(name) + data.typeParameters.set(typeParameters) + data.typeNode.set(typeNode) return f.newNode(KindTypeAliasDeclaration, data) } func (f *NodeFactory) NewJSTypeAliasDeclaration(modifiers *ModifierList, name *IdentifierNode, typeParameters *TypeParameterList, typeNode *TypeNode) *Node { - data := f.typeAliasDeclarationArena.New() - data.modifiers = modifiers - data.name = name - data.TypeParameters = typeParameters - data.Type = typeNode + data := newData[TypeAliasDeclaration](f) + data.modifiers.set(modifiers) + data.name.set(name) + data.typeParameters.set(typeParameters) + data.typeNode.set(typeNode) return f.newNode(KindJSTypeAliasDeclaration, data) } func (f *NodeFactory) UpdateTypeAliasDeclaration(node *TypeAliasDeclaration, modifiers *ModifierList, name *IdentifierNode, typeParameters *TypeParameterList, typeNode *TypeNode) *Node { - if modifiers != node.modifiers || name != node.name || typeParameters != node.TypeParameters || typeNode != node.Type { + if modifiers != node.modifiers.get() || name != node.name.get() || typeParameters != node.TypeParameters() || typeNode != node.Type() { switch node.Kind { case KindTypeAliasDeclaration: return updateNode(f.NewTypeAliasDeclaration(modifiers, name, typeParameters, typeNode), node.AsNode(), f.hooks) @@ -2293,29 +2615,29 @@ func (f *NodeFactory) UpdateTypeAliasDeclaration(node *TypeAliasDeclaration, mod } func (node *TypeAliasDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.name) || - visitNodeList(v, node.TypeParameters) || - visit(v, node.Type) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.name.get()) || + visitNodeList(v, node.TypeParameters()) || + visit(v, node.Type()) } func (node *TypeAliasDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateTypeAliasDeclaration(node, v.visitModifiers(node.modifiers), v.visitNode(node.name), v.visitNodes(node.TypeParameters), v.visitNode(node.Type)) + return v.Factory.UpdateTypeAliasDeclaration(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.name.get()), v.visitNodes(node.TypeParameters()), v.visitNode(node.Type())) } func (node *TypeAliasDeclaration) Clone(f NodeFactoryCoercible) *Node { switch node.Kind { case KindTypeAliasDeclaration: - return cloneNode(f.AsNodeFactory().NewTypeAliasDeclaration(node.Modifiers(), node.name, node.TypeParameters, node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewTypeAliasDeclaration(node.Modifiers(), node.name.get(), node.TypeParameters(), node.Type()), node.AsNode(), f.AsNodeFactory().hooks) case KindJSTypeAliasDeclaration: - return cloneNode(f.AsNodeFactory().NewJSTypeAliasDeclaration(node.Modifiers(), node.name, node.TypeParameters, node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSTypeAliasDeclaration(node.Modifiers(), node.name.get(), node.TypeParameters(), node.Type()), node.AsNode(), f.AsNodeFactory().hooks) default: panic("unexpected kind in TypeAliasDeclaration.Clone: " + node.Kind.String()) } } func (node *TypeAliasDeclaration) Name() *DeclarationName { - return node.name + return node.name.get() } func IsTypeAliasDeclaration(node *Node) bool { @@ -2335,37 +2657,41 @@ type EnumMember struct { DeclarationBase NamedMemberBase CompositeBase - Initializer *Expression // Optional + initializer link[Node] // *Expression. Optional } +func (node *EnumMember) Initializer() *Expression { return node.initializer.get() } + +func (node *EnumMember) SetInitializer(initializer *Expression) { node.initializer.set(initializer) } + func (f *NodeFactory) NewEnumMember(name *PropertyName, initializer *Expression) *Node { - data := &EnumMember{} - data.name = name - data.Initializer = initializer + data := newData[EnumMember](f) + data.name.set(name) + data.initializer.set(initializer) return f.newNode(KindEnumMember, data) } func (f *NodeFactory) UpdateEnumMember(node *EnumMember, name *PropertyName, initializer *Expression) *Node { - if name != node.name || initializer != node.Initializer { + if name != node.name.get() || initializer != node.Initializer() { return updateNode(f.NewEnumMember(name, initializer), node.AsNode(), f.hooks) } return node.AsNode() } func (node *EnumMember) ForEachChild(v Visitor) bool { - return visit(v, node.name) || visit(v, node.Initializer) + return visit(v, node.name.get()) || visit(v, node.Initializer()) } func (node *EnumMember) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateEnumMember(node, v.visitNode(node.name), v.visitNode(node.Initializer)) + return v.Factory.UpdateEnumMember(node, v.visitNode(node.name.get()), v.visitNode(node.Initializer())) } func (node *EnumMember) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewEnumMember(node.name, node.Initializer), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewEnumMember(node.name.get(), node.Initializer()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *EnumMember) Name() *DeclarationName { - return node.name + return node.name.get() } func IsEnumMember(node *Node) bool { @@ -2382,39 +2708,43 @@ type EnumDeclaration struct { ExportableBase ModifiersBase CompositeBase - name *IdentifierNode - Members *EnumMemberList + name link[Node] // *IdentifierNode + members link[NodeList] // *EnumMemberList } +func (node *EnumDeclaration) Members() *EnumMemberList { return node.members.get() } + +func (node *EnumDeclaration) SetMembers(members *EnumMemberList) { node.members.set(members) } + func (f *NodeFactory) NewEnumDeclaration(modifiers *ModifierList, name *IdentifierNode, members *EnumMemberList) *Node { - data := &EnumDeclaration{} - data.modifiers = modifiers - data.name = name - data.Members = members + data := newData[EnumDeclaration](f) + data.modifiers.set(modifiers) + data.name.set(name) + data.members.set(members) return f.newNode(KindEnumDeclaration, data) } func (f *NodeFactory) UpdateEnumDeclaration(node *EnumDeclaration, modifiers *ModifierList, name *IdentifierNode, members *EnumMemberList) *Node { - if modifiers != node.modifiers || name != node.name || members != node.Members { + if modifiers != node.modifiers.get() || name != node.name.get() || members != node.Members() { return updateNode(f.NewEnumDeclaration(modifiers, name, members), node.AsNode(), f.hooks) } return node.AsNode() } func (node *EnumDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || visit(v, node.name) || visitNodeList(v, node.Members) + return visitModifiers(v, node.modifiers.get()) || visit(v, node.name.get()) || visitNodeList(v, node.Members()) } func (node *EnumDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateEnumDeclaration(node, v.visitModifiers(node.modifiers), v.visitNode(node.name), v.visitNodes(node.Members)) + return v.Factory.UpdateEnumDeclaration(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.name.get()), v.visitNodes(node.Members())) } func (node *EnumDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewEnumDeclaration(node.Modifiers(), node.name, node.Members), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewEnumDeclaration(node.Modifiers(), node.name.get(), node.Members()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *EnumDeclaration) Name() *DeclarationName { - return node.name + return node.name.get() } func IsEnumDeclaration(node *Node) bool { @@ -2428,36 +2758,40 @@ func IsEnumDeclaration(node *Node) bool { type ModuleBlock struct { StatementBase CompositeBase - Statements *StatementList + statements link[NodeList] // *StatementList } +func (node *ModuleBlock) Statements() *StatementList { return node.statements.get() } + +func (node *ModuleBlock) SetStatements(statements *StatementList) { node.statements.set(statements) } + func (f *NodeFactory) NewModuleBlock(statements *StatementList) *Node { - data := &ModuleBlock{} - data.Statements = statements + data := newData[ModuleBlock](f) + data.statements.set(statements) return f.newNode(KindModuleBlock, data) } func (f *NodeFactory) UpdateModuleBlock(node *ModuleBlock, statements *StatementList) *Node { - if statements != node.Statements { + if statements != node.Statements() { return updateNode(f.NewModuleBlock(statements), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ModuleBlock) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.Statements) + return visitNodeList(v, node.Statements()) } func (node *ModuleBlock) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateModuleBlock(node, v.visitNodes(node.Statements)) + return v.Factory.UpdateModuleBlock(node, v.visitNodes(node.Statements())) } func (node *ModuleBlock) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewModuleBlock(node.Statements), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewModuleBlock(node.Statements()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ModuleBlock) computeSubtreeFacts() SubtreeFacts { - return propagateNodeListSubtreeFacts(node.Statements, propagateSubtreeFacts) + return propagateNodeListSubtreeFacts(node.Statements(), propagateSubtreeFacts) } func IsModuleBlock(node *Node) bool { @@ -2473,7 +2807,7 @@ type NotEmittedStatement struct { } func (f *NodeFactory) NewNotEmittedStatement() *Node { - data := &NotEmittedStatement{} + data := newData[NotEmittedStatement](f) return f.newNode(KindNotEmittedStatement, data) } @@ -2496,7 +2830,7 @@ type NotEmittedTypeElement struct { } func (f *NodeFactory) NewNotEmittedTypeElement() *Node { - data := &NotEmittedTypeElement{} + data := newData[NotEmittedTypeElement](f) return f.newNode(KindNotEmittedTypeElement, data) } @@ -2517,31 +2851,49 @@ type ImportDeclaration struct { ModifiersBase CompositeBase DeclarationBase - ImportClause *ImportClauseNode // Optional - ModuleSpecifier *Expression - Attributes *ImportAttributesNode // Optional + importClause link[Node] // *ImportClauseNode. Optional + moduleSpecifier link[Node] // *Expression + attributes link[Node] // *ImportAttributesNode. Optional +} + +func (node *ImportDeclaration) ImportClause() *ImportClauseNode { return node.importClause.get() } + +func (node *ImportDeclaration) SetImportClause(importClause *ImportClauseNode) { + node.importClause.set(importClause) +} + +func (node *ImportDeclaration) ModuleSpecifier() *Expression { return node.moduleSpecifier.get() } + +func (node *ImportDeclaration) SetModuleSpecifier(moduleSpecifier *Expression) { + node.moduleSpecifier.set(moduleSpecifier) +} + +func (node *ImportDeclaration) Attributes() *ImportAttributesNode { return node.attributes.get() } + +func (node *ImportDeclaration) SetAttributes(attributes *ImportAttributesNode) { + node.attributes.set(attributes) } func (f *NodeFactory) NewImportDeclaration(modifiers *ModifierList, importClause *ImportClauseNode, moduleSpecifier *Expression, attributes *ImportAttributesNode) *Node { - data := &ImportDeclaration{} - data.modifiers = modifiers - data.ImportClause = importClause - data.ModuleSpecifier = moduleSpecifier - data.Attributes = attributes + data := newData[ImportDeclaration](f) + data.modifiers.set(modifiers) + data.importClause.set(importClause) + data.moduleSpecifier.set(moduleSpecifier) + data.attributes.set(attributes) return f.newNode(KindImportDeclaration, data) } func (f *NodeFactory) NewJSImportDeclaration(modifiers *ModifierList, importClause *ImportClauseNode, moduleSpecifier *Expression, attributes *ImportAttributesNode) *Node { - data := &ImportDeclaration{} - data.modifiers = modifiers - data.ImportClause = importClause - data.ModuleSpecifier = moduleSpecifier - data.Attributes = attributes + data := newData[ImportDeclaration](f) + data.modifiers.set(modifiers) + data.importClause.set(importClause) + data.moduleSpecifier.set(moduleSpecifier) + data.attributes.set(attributes) return f.newNode(KindJSImportDeclaration, data) } func (f *NodeFactory) UpdateImportDeclaration(node *ImportDeclaration, modifiers *ModifierList, importClause *ImportClauseNode, moduleSpecifier *Expression, attributes *ImportAttributesNode) *Node { - if modifiers != node.modifiers || importClause != node.ImportClause || moduleSpecifier != node.ModuleSpecifier || attributes != node.Attributes { + if modifiers != node.modifiers.get() || importClause != node.ImportClause() || moduleSpecifier != node.ModuleSpecifier() || attributes != node.Attributes() { switch node.Kind { case KindImportDeclaration: return updateNode(f.NewImportDeclaration(modifiers, importClause, moduleSpecifier, attributes), node.AsNode(), f.hooks) @@ -2555,32 +2907,32 @@ func (f *NodeFactory) UpdateImportDeclaration(node *ImportDeclaration, modifiers } func (node *ImportDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.ImportClause) || - visit(v, node.ModuleSpecifier) || - visit(v, node.Attributes) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.ImportClause()) || + visit(v, node.ModuleSpecifier()) || + visit(v, node.Attributes()) } func (node *ImportDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateImportDeclaration(node, v.visitModifiers(node.modifiers), v.visitNode(node.ImportClause), v.visitNode(node.ModuleSpecifier), v.visitNode(node.Attributes)) + return v.Factory.UpdateImportDeclaration(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.ImportClause()), v.visitNode(node.ModuleSpecifier()), v.visitNode(node.Attributes())) } func (node *ImportDeclaration) Clone(f NodeFactoryCoercible) *Node { switch node.Kind { case KindImportDeclaration: - return cloneNode(f.AsNodeFactory().NewImportDeclaration(node.Modifiers(), node.ImportClause, node.ModuleSpecifier, node.Attributes), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewImportDeclaration(node.Modifiers(), node.ImportClause(), node.ModuleSpecifier(), node.Attributes()), node.AsNode(), f.AsNodeFactory().hooks) case KindJSImportDeclaration: - return cloneNode(f.AsNodeFactory().NewJSImportDeclaration(node.Modifiers(), node.ImportClause, node.ModuleSpecifier, node.Attributes), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSImportDeclaration(node.Modifiers(), node.ImportClause(), node.ModuleSpecifier(), node.Attributes()), node.AsNode(), f.AsNodeFactory().hooks) default: panic("unexpected kind in ImportDeclaration.Clone: " + node.Kind.String()) } } func (node *ImportDeclaration) computeSubtreeFacts() SubtreeFacts { - return propagateModifierListSubtreeFacts(node.modifiers) | - propagateSubtreeFacts(node.ImportClause) | - propagateSubtreeFacts(node.ModuleSpecifier) | - propagateSubtreeFacts(node.Attributes) + return propagateModifierListSubtreeFacts(node.modifiers.get()) | + propagateSubtreeFacts(node.ImportClause()) | + propagateSubtreeFacts(node.ModuleSpecifier()) | + propagateSubtreeFacts(node.Attributes()) } func IsImportDeclaration(node *Node) bool { @@ -2597,36 +2949,42 @@ func IsJSImportDeclaration(node *Node) bool { type ExternalModuleReference struct { NodeBase - Expression *Expression + expression link[Node] // *Expression +} + +func (node *ExternalModuleReference) Expression() *Expression { return node.expression.get() } + +func (node *ExternalModuleReference) SetExpression(expression *Expression) { + node.expression.set(expression) } func (f *NodeFactory) NewExternalModuleReference(expression *Expression) *Node { - data := &ExternalModuleReference{} - data.Expression = expression + data := newData[ExternalModuleReference](f) + data.expression.set(expression) return f.newNode(KindExternalModuleReference, data) } func (f *NodeFactory) UpdateExternalModuleReference(node *ExternalModuleReference, expression *Expression) *Node { - if expression != node.Expression { + if expression != node.Expression() { return updateNode(f.NewExternalModuleReference(expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ExternalModuleReference) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) + return visit(v, node.Expression()) } func (node *ExternalModuleReference) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateExternalModuleReference(node, v.visitNode(node.Expression)) + return v.Factory.UpdateExternalModuleReference(node, v.visitNode(node.Expression())) } func (node *ExternalModuleReference) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewExternalModuleReference(node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewExternalModuleReference(node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ExternalModuleReference) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) + return propagateSubtreeFacts(node.Expression()) } func IsExternalModuleReference(node *Node) bool { @@ -2641,40 +2999,40 @@ type NamespaceImport struct { NodeBase DeclarationBase ExportableBase - name *IdentifierNode + name link[Node] // *IdentifierNode } func (f *NodeFactory) NewNamespaceImport(name *IdentifierNode) *Node { - data := &NamespaceImport{} - data.name = name + data := newData[NamespaceImport](f) + data.name.set(name) return f.newNode(KindNamespaceImport, data) } func (f *NodeFactory) UpdateNamespaceImport(node *NamespaceImport, name *IdentifierNode) *Node { - if name != node.name { + if name != node.name.get() { return updateNode(f.NewNamespaceImport(name), node.AsNode(), f.hooks) } return node.AsNode() } func (node *NamespaceImport) ForEachChild(v Visitor) bool { - return visit(v, node.name) + return visit(v, node.name.get()) } func (node *NamespaceImport) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateNamespaceImport(node, v.visitNode(node.name)) + return v.Factory.UpdateNamespaceImport(node, v.visitNode(node.name.get())) } func (node *NamespaceImport) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewNamespaceImport(node.name), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewNamespaceImport(node.name.get()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *NamespaceImport) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.name) + return propagateSubtreeFacts(node.name.get()) } func (node *NamespaceImport) Name() *DeclarationName { - return node.name + return node.name.get() } func IsNamespaceImport(node *Node) bool { @@ -2688,36 +3046,40 @@ func IsNamespaceImport(node *Node) bool { type NamedImports struct { NodeBase CompositeBase - Elements *ImportSpecifierList + elements link[NodeList] // *ImportSpecifierList } +func (node *NamedImports) Elements() *ImportSpecifierList { return node.elements.get() } + +func (node *NamedImports) SetElements(elements *ImportSpecifierList) { node.elements.set(elements) } + func (f *NodeFactory) NewNamedImports(elements *ImportSpecifierList) *Node { - data := &NamedImports{} - data.Elements = elements + data := newData[NamedImports](f) + data.elements.set(elements) return f.newNode(KindNamedImports, data) } func (f *NodeFactory) UpdateNamedImports(node *NamedImports, elements *ImportSpecifierList) *Node { - if elements != node.Elements { + if elements != node.Elements() { return updateNode(f.NewNamedImports(elements), node.AsNode(), f.hooks) } return node.AsNode() } func (node *NamedImports) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.Elements) + return visitNodeList(v, node.Elements()) } func (node *NamedImports) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateNamedImports(node, v.visitNodes(node.Elements)) + return v.Factory.UpdateNamedImports(node, v.visitNodes(node.Elements())) } func (node *NamedImports) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewNamedImports(node.Elements), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewNamedImports(node.Elements()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *NamedImports) computeSubtreeFacts() SubtreeFacts { - return propagateNodeListSubtreeFacts(node.Elements, propagateSubtreeFacts) + return propagateNodeListSubtreeFacts(node.Elements(), propagateSubtreeFacts) } func IsNamedImports(node *Node) bool { @@ -2734,36 +3096,44 @@ type ExportAssignment struct { ModifiersBase CompositeBase IsExportEquals bool - Type *TypeNode - Expression *Expression + typeNode link[Node] // *TypeNode + expression link[Node] // *Expression } +func (node *ExportAssignment) Type() *TypeNode { return node.typeNode.get() } + +func (node *ExportAssignment) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + +func (node *ExportAssignment) Expression() *Expression { return node.expression.get() } + +func (node *ExportAssignment) SetExpression(expression *Expression) { node.expression.set(expression) } + func (f *NodeFactory) NewExportAssignment(modifiers *ModifierList, isExportEquals bool, typeNode *TypeNode, expression *Expression) *Node { - data := &ExportAssignment{} - data.modifiers = modifiers + data := newData[ExportAssignment](f) + data.modifiers.set(modifiers) data.IsExportEquals = isExportEquals - data.Type = typeNode - data.Expression = expression + data.typeNode.set(typeNode) + data.expression.set(expression) return f.newNode(KindExportAssignment, data) } func (f *NodeFactory) UpdateExportAssignment(node *ExportAssignment, modifiers *ModifierList, isExportEquals bool, typeNode *TypeNode, expression *Expression) *Node { - if modifiers != node.modifiers || isExportEquals != node.IsExportEquals || typeNode != node.Type || expression != node.Expression { + if modifiers != node.modifiers.get() || isExportEquals != node.IsExportEquals || typeNode != node.Type() || expression != node.Expression() { return updateNode(f.NewExportAssignment(modifiers, isExportEquals, typeNode, expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ExportAssignment) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || visit(v, node.Type) || visit(v, node.Expression) + return visitModifiers(v, node.modifiers.get()) || visit(v, node.Type()) || visit(v, node.Expression()) } func (node *ExportAssignment) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateExportAssignment(node, v.visitModifiers(node.modifiers), node.IsExportEquals, v.visitNode(node.Type), v.visitNode(node.Expression)) + return v.Factory.UpdateExportAssignment(node, v.visitModifiers(node.modifiers.get()), node.IsExportEquals, v.visitNode(node.Type()), v.visitNode(node.Expression())) } func (node *ExportAssignment) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewExportAssignment(node.Modifiers(), node.IsExportEquals, node.Type, node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewExportAssignment(node.Modifiers(), node.IsExportEquals, node.Type(), node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func IsExportAssignment(node *Node) bool { @@ -2779,37 +3149,37 @@ type NamespaceExportDeclaration struct { StatementBase DeclarationBase ModifiersBase - name *IdentifierNode + name link[Node] // *IdentifierNode } func (f *NodeFactory) NewNamespaceExportDeclaration(modifiers *ModifierList, name *IdentifierNode) *Node { - data := &NamespaceExportDeclaration{} - data.modifiers = modifiers - data.name = name + data := newData[NamespaceExportDeclaration](f) + data.modifiers.set(modifiers) + data.name.set(name) return f.newNode(KindNamespaceExportDeclaration, data) } func (f *NodeFactory) UpdateNamespaceExportDeclaration(node *NamespaceExportDeclaration, modifiers *ModifierList, name *IdentifierNode) *Node { - if modifiers != node.modifiers || name != node.name { + if modifiers != node.modifiers.get() || name != node.name.get() { return updateNode(f.NewNamespaceExportDeclaration(modifiers, name), node.AsNode(), f.hooks) } return node.AsNode() } func (node *NamespaceExportDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || visit(v, node.name) + return visitModifiers(v, node.modifiers.get()) || visit(v, node.name.get()) } func (node *NamespaceExportDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateNamespaceExportDeclaration(node, v.visitModifiers(node.modifiers), v.visitNode(node.name)) + return v.Factory.UpdateNamespaceExportDeclaration(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.name.get())) } func (node *NamespaceExportDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewNamespaceExportDeclaration(node.Modifiers(), node.name), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewNamespaceExportDeclaration(node.Modifiers(), node.name.get()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *NamespaceExportDeclaration) Name() *DeclarationName { - return node.name + return node.name.get() } func IsNamespaceExportDeclaration(node *Node) bool { @@ -2823,40 +3193,40 @@ func IsNamespaceExportDeclaration(node *Node) bool { type NamespaceExport struct { NodeBase DeclarationBase - name *ModuleExportName + name link[Node] // *ModuleExportName } func (f *NodeFactory) NewNamespaceExport(name *ModuleExportName) *Node { - data := &NamespaceExport{} - data.name = name + data := newData[NamespaceExport](f) + data.name.set(name) return f.newNode(KindNamespaceExport, data) } func (f *NodeFactory) UpdateNamespaceExport(node *NamespaceExport, name *ModuleExportName) *Node { - if name != node.name { + if name != node.name.get() { return updateNode(f.NewNamespaceExport(name), node.AsNode(), f.hooks) } return node.AsNode() } func (node *NamespaceExport) ForEachChild(v Visitor) bool { - return visit(v, node.name) + return visit(v, node.name.get()) } func (node *NamespaceExport) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateNamespaceExport(node, v.visitNode(node.name)) + return v.Factory.UpdateNamespaceExport(node, v.visitNode(node.name.get())) } func (node *NamespaceExport) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewNamespaceExport(node.name), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewNamespaceExport(node.name.get()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *NamespaceExport) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.name) + return propagateSubtreeFacts(node.name.get()) } func (node *NamespaceExport) Name() *DeclarationName { - return node.name + return node.name.get() } func IsNamespaceExport(node *Node) bool { @@ -2870,36 +3240,40 @@ func IsNamespaceExport(node *Node) bool { type NamedExports struct { NodeBase CompositeBase - Elements *ExportSpecifierList + elements link[NodeList] // *ExportSpecifierList } +func (node *NamedExports) Elements() *ExportSpecifierList { return node.elements.get() } + +func (node *NamedExports) SetElements(elements *ExportSpecifierList) { node.elements.set(elements) } + func (f *NodeFactory) NewNamedExports(elements *ExportSpecifierList) *Node { - data := &NamedExports{} - data.Elements = elements + data := newData[NamedExports](f) + data.elements.set(elements) return f.newNode(KindNamedExports, data) } func (f *NodeFactory) UpdateNamedExports(node *NamedExports, elements *ExportSpecifierList) *Node { - if elements != node.Elements { + if elements != node.Elements() { return updateNode(f.NewNamedExports(elements), node.AsNode(), f.hooks) } return node.AsNode() } func (node *NamedExports) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.Elements) + return visitNodeList(v, node.Elements()) } func (node *NamedExports) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateNamedExports(node, v.visitNodes(node.Elements)) + return v.Factory.UpdateNamedExports(node, v.visitNodes(node.Elements())) } func (node *NamedExports) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewNamedExports(node.Elements), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewNamedExports(node.Elements()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *NamedExports) computeSubtreeFacts() SubtreeFacts { - return propagateNodeListSubtreeFacts(node.Elements, propagateSubtreeFacts) + return propagateNodeListSubtreeFacts(node.Elements(), propagateSubtreeFacts) } func IsNamedExports(node *Node) bool { @@ -2916,39 +3290,45 @@ type ExportSpecifier struct { ExportableBase CompositeBase IsTypeOnly bool - PropertyName *ModuleExportName // Optional - name *ModuleExportName + propertyName link[Node] // *ModuleExportName. Optional + name link[Node] // *ModuleExportName +} + +func (node *ExportSpecifier) PropertyName() *ModuleExportName { return node.propertyName.get() } + +func (node *ExportSpecifier) SetPropertyName(propertyName *ModuleExportName) { + node.propertyName.set(propertyName) } func (f *NodeFactory) NewExportSpecifier(isTypeOnly bool, propertyName *ModuleExportName, name *ModuleExportName) *Node { - data := &ExportSpecifier{} + data := newData[ExportSpecifier](f) data.IsTypeOnly = isTypeOnly - data.PropertyName = propertyName - data.name = name + data.propertyName.set(propertyName) + data.name.set(name) return f.newNode(KindExportSpecifier, data) } func (f *NodeFactory) UpdateExportSpecifier(node *ExportSpecifier, isTypeOnly bool, propertyName *ModuleExportName, name *ModuleExportName) *Node { - if isTypeOnly != node.IsTypeOnly || propertyName != node.PropertyName || name != node.name { + if isTypeOnly != node.IsTypeOnly || propertyName != node.PropertyName() || name != node.name.get() { return updateNode(f.NewExportSpecifier(isTypeOnly, propertyName, name), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ExportSpecifier) ForEachChild(v Visitor) bool { - return visit(v, node.PropertyName) || visit(v, node.name) + return visit(v, node.PropertyName()) || visit(v, node.name.get()) } func (node *ExportSpecifier) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateExportSpecifier(node, node.IsTypeOnly, v.visitNode(node.PropertyName), v.visitNode(node.name)) + return v.Factory.UpdateExportSpecifier(node, node.IsTypeOnly, v.visitNode(node.PropertyName()), v.visitNode(node.name.get())) } func (node *ExportSpecifier) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewExportSpecifier(node.IsTypeOnly, node.PropertyName, node.name), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewExportSpecifier(node.IsTypeOnly, node.PropertyName(), node.name.get()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ExportSpecifier) Name() *DeclarationName { - return node.name + return node.name.get() } func IsExportSpecifier(node *Node) bool { @@ -2968,30 +3348,30 @@ type CallSignatureDeclaration struct { } func (f *NodeFactory) NewCallSignatureDeclaration(typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode) *Node { - data := &CallSignatureDeclaration{} - data.TypeParameters = typeParameters - data.Parameters = parameters - data.Type = typeNode + data := newData[CallSignatureDeclaration](f) + data.typeParameters.set(typeParameters) + data.parameters.set(parameters) + data.typeNode.set(typeNode) return f.newNode(KindCallSignature, data) } func (f *NodeFactory) UpdateCallSignatureDeclaration(node *CallSignatureDeclaration, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode) *Node { - if typeParameters != node.TypeParameters || parameters != node.Parameters || typeNode != node.Type { + if typeParameters != node.TypeParameters() || parameters != node.Parameters() || typeNode != node.Type() { return updateNode(f.NewCallSignatureDeclaration(typeParameters, parameters, typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *CallSignatureDeclaration) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.TypeParameters) || visitNodeList(v, node.Parameters) || visit(v, node.Type) + return visitNodeList(v, node.TypeParameters()) || visitNodeList(v, node.Parameters()) || visit(v, node.Type()) } func (node *CallSignatureDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateCallSignatureDeclaration(node, v.visitNodes(node.TypeParameters), v.visitNodes(node.Parameters), v.visitNode(node.Type)) + return v.Factory.UpdateCallSignatureDeclaration(node, v.visitNodes(node.TypeParameters()), v.visitNodes(node.Parameters()), v.visitNode(node.Type())) } func (node *CallSignatureDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewCallSignatureDeclaration(node.TypeParameters, node.Parameters, node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewCallSignatureDeclaration(node.TypeParameters(), node.Parameters(), node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func IsCallSignatureDeclaration(node *Node) bool { @@ -3011,30 +3391,30 @@ type ConstructSignatureDeclaration struct { } func (f *NodeFactory) NewConstructSignatureDeclaration(typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode) *Node { - data := f.constructSignatureDeclarationArena.New() - data.TypeParameters = typeParameters - data.Parameters = parameters - data.Type = typeNode + data := newData[ConstructSignatureDeclaration](f) + data.typeParameters.set(typeParameters) + data.parameters.set(parameters) + data.typeNode.set(typeNode) return f.newNode(KindConstructSignature, data) } func (f *NodeFactory) UpdateConstructSignatureDeclaration(node *ConstructSignatureDeclaration, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode) *Node { - if typeParameters != node.TypeParameters || parameters != node.Parameters || typeNode != node.Type { + if typeParameters != node.TypeParameters() || parameters != node.Parameters() || typeNode != node.Type() { return updateNode(f.NewConstructSignatureDeclaration(typeParameters, parameters, typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ConstructSignatureDeclaration) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.TypeParameters) || visitNodeList(v, node.Parameters) || visit(v, node.Type) + return visitNodeList(v, node.TypeParameters()) || visitNodeList(v, node.Parameters()) || visit(v, node.Type()) } func (node *ConstructSignatureDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateConstructSignatureDeclaration(node, v.visitNodes(node.TypeParameters), v.visitNodes(node.Parameters), v.visitNode(node.Type)) + return v.Factory.UpdateConstructSignatureDeclaration(node, v.visitNodes(node.TypeParameters()), v.visitNodes(node.Parameters()), v.visitNode(node.Type())) } func (node *ConstructSignatureDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewConstructSignatureDeclaration(node.TypeParameters, node.Parameters, node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewConstructSignatureDeclaration(node.TypeParameters(), node.Parameters(), node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func IsConstructSignatureDeclaration(node *Node) bool { @@ -3056,38 +3436,38 @@ type ConstructorDeclaration struct { } func (f *NodeFactory) NewConstructorDeclaration(modifiers *ModifierList, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode, fullSignature *TypeNode, body *FunctionBody) *Node { - data := &ConstructorDeclaration{} - data.modifiers = modifiers - data.TypeParameters = typeParameters - data.Parameters = parameters - data.Type = typeNode - data.FullSignature = fullSignature - data.Body = body + data := newData[ConstructorDeclaration](f) + data.modifiers.set(modifiers) + data.typeParameters.set(typeParameters) + data.parameters.set(parameters) + data.typeNode.set(typeNode) + data.fullSignature.set(fullSignature) + data.body.set(body) return f.newNode(KindConstructor, data) } func (f *NodeFactory) UpdateConstructorDeclaration(node *ConstructorDeclaration, modifiers *ModifierList, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode, fullSignature *TypeNode, body *FunctionBody) *Node { - if modifiers != node.modifiers || typeParameters != node.TypeParameters || parameters != node.Parameters || typeNode != node.Type || fullSignature != node.FullSignature || body != node.Body { + if modifiers != node.modifiers.get() || typeParameters != node.TypeParameters() || parameters != node.Parameters() || typeNode != node.Type() || fullSignature != node.FullSignature() || body != node.Body() { return updateNode(f.NewConstructorDeclaration(modifiers, typeParameters, parameters, typeNode, fullSignature, body), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ConstructorDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visitNodeList(v, node.TypeParameters) || - visitNodeList(v, node.Parameters) || - visit(v, node.Type) || - visit(v, node.FullSignature) || - visit(v, node.Body) + return visitModifiers(v, node.modifiers.get()) || + visitNodeList(v, node.TypeParameters()) || + visitNodeList(v, node.Parameters()) || + visit(v, node.Type()) || + visit(v, node.FullSignature()) || + visit(v, node.Body()) } func (node *ConstructorDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateConstructorDeclaration(node, v.visitModifiers(node.modifiers), v.visitNodes(node.TypeParameters), v.visitParameters(node.Parameters), v.visitNode(node.Type), v.visitNode(node.FullSignature), v.visitFunctionBody(node.Body)) + return v.Factory.UpdateConstructorDeclaration(node, v.visitModifiers(node.modifiers.get()), v.visitNodes(node.TypeParameters()), v.visitParameters(node.Parameters()), v.visitNode(node.Type()), v.visitNode(node.FullSignature()), v.visitFunctionBody(node.Body())) } func (node *ConstructorDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewConstructorDeclaration(node.Modifiers(), node.TypeParameters, node.Parameters, node.Type, node.FullSignature, node.Body), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewConstructorDeclaration(node.Modifiers(), node.TypeParameters(), node.Parameters(), node.Type(), node.FullSignature(), node.Body()), node.AsNode(), f.AsNodeFactory().hooks) } func IsConstructorDeclaration(node *Node) bool { @@ -3103,44 +3483,44 @@ type GetAccessorDeclaration struct { } func (f *NodeFactory) NewGetAccessorDeclaration(modifiers *ModifierList, name *PropertyName, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode, fullSignature *TypeNode, body *FunctionBody) *Node { - data := &GetAccessorDeclaration{} - data.modifiers = modifiers - data.name = name - data.TypeParameters = typeParameters - data.Parameters = parameters - data.Type = typeNode - data.FullSignature = fullSignature - data.Body = body + data := newData[GetAccessorDeclaration](f) + data.modifiers.set(modifiers) + data.name.set(name) + data.typeParameters.set(typeParameters) + data.parameters.set(parameters) + data.typeNode.set(typeNode) + data.fullSignature.set(fullSignature) + data.body.set(body) return f.newNode(KindGetAccessor, data) } func (f *NodeFactory) UpdateGetAccessorDeclaration(node *GetAccessorDeclaration, modifiers *ModifierList, name *PropertyName, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode, fullSignature *TypeNode, body *FunctionBody) *Node { - if modifiers != node.modifiers || name != node.name || typeParameters != node.TypeParameters || parameters != node.Parameters || typeNode != node.Type || fullSignature != node.FullSignature || body != node.Body { + if modifiers != node.modifiers.get() || name != node.name.get() || typeParameters != node.TypeParameters() || parameters != node.Parameters() || typeNode != node.Type() || fullSignature != node.FullSignature() || body != node.Body() { return updateNode(f.NewGetAccessorDeclaration(modifiers, name, typeParameters, parameters, typeNode, fullSignature, body), node.AsNode(), f.hooks) } return node.AsNode() } func (node *GetAccessorDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.name) || - visitNodeList(v, node.TypeParameters) || - visitNodeList(v, node.Parameters) || - visit(v, node.Type) || - visit(v, node.FullSignature) || - visit(v, node.Body) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.name.get()) || + visitNodeList(v, node.TypeParameters()) || + visitNodeList(v, node.Parameters()) || + visit(v, node.Type()) || + visit(v, node.FullSignature()) || + visit(v, node.Body()) } func (node *GetAccessorDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateGetAccessorDeclaration(node, v.visitModifiers(node.modifiers), v.visitNode(node.name), v.visitNodes(node.TypeParameters), v.visitParameters(node.Parameters), v.visitNode(node.Type), v.visitNode(node.FullSignature), v.visitFunctionBody(node.Body)) + return v.Factory.UpdateGetAccessorDeclaration(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.name.get()), v.visitNodes(node.TypeParameters()), v.visitParameters(node.Parameters()), v.visitNode(node.Type()), v.visitNode(node.FullSignature()), v.visitFunctionBody(node.Body())) } func (node *GetAccessorDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewGetAccessorDeclaration(node.Modifiers(), node.name, node.TypeParameters, node.Parameters, node.Type, node.FullSignature, node.Body), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewGetAccessorDeclaration(node.Modifiers(), node.name.get(), node.TypeParameters(), node.Parameters(), node.Type(), node.FullSignature(), node.Body()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *GetAccessorDeclaration) Name() *DeclarationName { - return node.name + return node.name.get() } func IsGetAccessorDeclaration(node *Node) bool { @@ -3156,44 +3536,44 @@ type SetAccessorDeclaration struct { } func (f *NodeFactory) NewSetAccessorDeclaration(modifiers *ModifierList, name *PropertyName, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode, fullSignature *TypeNode, body *FunctionBody) *Node { - data := &SetAccessorDeclaration{} - data.modifiers = modifiers - data.name = name - data.TypeParameters = typeParameters - data.Parameters = parameters - data.Type = typeNode - data.FullSignature = fullSignature - data.Body = body + data := newData[SetAccessorDeclaration](f) + data.modifiers.set(modifiers) + data.name.set(name) + data.typeParameters.set(typeParameters) + data.parameters.set(parameters) + data.typeNode.set(typeNode) + data.fullSignature.set(fullSignature) + data.body.set(body) return f.newNode(KindSetAccessor, data) } func (f *NodeFactory) UpdateSetAccessorDeclaration(node *SetAccessorDeclaration, modifiers *ModifierList, name *PropertyName, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode, fullSignature *TypeNode, body *FunctionBody) *Node { - if modifiers != node.modifiers || name != node.name || typeParameters != node.TypeParameters || parameters != node.Parameters || typeNode != node.Type || fullSignature != node.FullSignature || body != node.Body { + if modifiers != node.modifiers.get() || name != node.name.get() || typeParameters != node.TypeParameters() || parameters != node.Parameters() || typeNode != node.Type() || fullSignature != node.FullSignature() || body != node.Body() { return updateNode(f.NewSetAccessorDeclaration(modifiers, name, typeParameters, parameters, typeNode, fullSignature, body), node.AsNode(), f.hooks) } return node.AsNode() } func (node *SetAccessorDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.name) || - visitNodeList(v, node.TypeParameters) || - visitNodeList(v, node.Parameters) || - visit(v, node.Type) || - visit(v, node.FullSignature) || - visit(v, node.Body) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.name.get()) || + visitNodeList(v, node.TypeParameters()) || + visitNodeList(v, node.Parameters()) || + visit(v, node.Type()) || + visit(v, node.FullSignature()) || + visit(v, node.Body()) } func (node *SetAccessorDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateSetAccessorDeclaration(node, v.visitModifiers(node.modifiers), v.visitNode(node.name), v.visitNodes(node.TypeParameters), v.visitParameters(node.Parameters), v.visitNode(node.Type), v.visitNode(node.FullSignature), v.visitFunctionBody(node.Body)) + return v.Factory.UpdateSetAccessorDeclaration(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.name.get()), v.visitNodes(node.TypeParameters()), v.visitParameters(node.Parameters()), v.visitNode(node.Type()), v.visitNode(node.FullSignature()), v.visitFunctionBody(node.Body())) } func (node *SetAccessorDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewSetAccessorDeclaration(node.Modifiers(), node.name, node.TypeParameters, node.Parameters, node.Type, node.FullSignature, node.Body), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewSetAccessorDeclaration(node.Modifiers(), node.name.get(), node.TypeParameters(), node.Parameters(), node.Type(), node.FullSignature(), node.Body()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *SetAccessorDeclaration) Name() *DeclarationName { - return node.name + return node.name.get() } func IsSetAccessorDeclaration(node *Node) bool { @@ -3215,30 +3595,30 @@ type IndexSignatureDeclaration struct { } func (f *NodeFactory) NewIndexSignatureDeclaration(modifiers *ModifierList, parameters *ParameterList, typeNode *TypeNode) *Node { - data := &IndexSignatureDeclaration{} - data.modifiers = modifiers - data.Parameters = parameters - data.Type = typeNode + data := newData[IndexSignatureDeclaration](f) + data.modifiers.set(modifiers) + data.parameters.set(parameters) + data.typeNode.set(typeNode) return f.newNode(KindIndexSignature, data) } func (f *NodeFactory) UpdateIndexSignatureDeclaration(node *IndexSignatureDeclaration, modifiers *ModifierList, parameters *ParameterList, typeNode *TypeNode) *Node { - if modifiers != node.modifiers || parameters != node.Parameters || typeNode != node.Type { + if modifiers != node.modifiers.get() || parameters != node.Parameters() || typeNode != node.Type() { return updateNode(f.NewIndexSignatureDeclaration(modifiers, parameters, typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *IndexSignatureDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || visitNodeList(v, node.Parameters) || visit(v, node.Type) + return visitModifiers(v, node.modifiers.get()) || visitNodeList(v, node.Parameters()) || visit(v, node.Type()) } func (node *IndexSignatureDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateIndexSignatureDeclaration(node, v.visitModifiers(node.modifiers), v.visitNodes(node.Parameters), v.visitNode(node.Type)) + return v.Factory.UpdateIndexSignatureDeclaration(node, v.visitModifiers(node.modifiers.get()), v.visitNodes(node.Parameters()), v.visitNode(node.Type())) } func (node *IndexSignatureDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewIndexSignatureDeclaration(node.Modifiers(), node.Parameters, node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewIndexSignatureDeclaration(node.Modifiers(), node.Parameters(), node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func IsIndexSignatureDeclaration(node *Node) bool { @@ -3259,42 +3639,42 @@ type MethodSignatureDeclaration struct { } func (f *NodeFactory) NewMethodSignatureDeclaration(modifiers *ModifierList, name *PropertyName, postfixToken *TokenNode, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode) *Node { - data := f.methodSignatureDeclarationArena.New() - data.modifiers = modifiers - data.name = name - data.PostfixToken = postfixToken - data.TypeParameters = typeParameters - data.Parameters = parameters - data.Type = typeNode + data := newData[MethodSignatureDeclaration](f) + data.modifiers.set(modifiers) + data.name.set(name) + data.postfixToken.set(postfixToken) + data.typeParameters.set(typeParameters) + data.parameters.set(parameters) + data.typeNode.set(typeNode) return f.newNode(KindMethodSignature, data) } func (f *NodeFactory) UpdateMethodSignatureDeclaration(node *MethodSignatureDeclaration, modifiers *ModifierList, name *PropertyName, postfixToken *TokenNode, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode) *Node { - if modifiers != node.modifiers || name != node.name || postfixToken != node.PostfixToken || typeParameters != node.TypeParameters || parameters != node.Parameters || typeNode != node.Type { + if modifiers != node.modifiers.get() || name != node.name.get() || postfixToken != node.PostfixToken() || typeParameters != node.TypeParameters() || parameters != node.Parameters() || typeNode != node.Type() { return updateNode(f.NewMethodSignatureDeclaration(modifiers, name, postfixToken, typeParameters, parameters, typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *MethodSignatureDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.name) || - visit(v, node.PostfixToken) || - visitNodeList(v, node.TypeParameters) || - visitNodeList(v, node.Parameters) || - visit(v, node.Type) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.name.get()) || + visit(v, node.PostfixToken()) || + visitNodeList(v, node.TypeParameters()) || + visitNodeList(v, node.Parameters()) || + visit(v, node.Type()) } func (node *MethodSignatureDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateMethodSignatureDeclaration(node, v.visitModifiers(node.modifiers), v.visitNode(node.name), v.visitNode(node.PostfixToken), v.visitNodes(node.TypeParameters), v.visitNodes(node.Parameters), v.visitNode(node.Type)) + return v.Factory.UpdateMethodSignatureDeclaration(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.name.get()), v.visitNode(node.PostfixToken()), v.visitNodes(node.TypeParameters()), v.visitNodes(node.Parameters()), v.visitNode(node.Type())) } func (node *MethodSignatureDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewMethodSignatureDeclaration(node.Modifiers(), node.name, node.PostfixToken, node.TypeParameters, node.Parameters, node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewMethodSignatureDeclaration(node.Modifiers(), node.name.get(), node.PostfixToken(), node.TypeParameters(), node.Parameters(), node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *MethodSignatureDeclaration) Name() *DeclarationName { - return node.name + return node.name.get() } func IsMethodSignatureDeclaration(node *Node) bool { @@ -3317,48 +3697,48 @@ type MethodDeclaration struct { } func (f *NodeFactory) NewMethodDeclaration(modifiers *ModifierList, asteriskToken *AsteriskToken, name *PropertyName, postfixToken *TokenNode, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode, fullSignature *TypeNode, body *FunctionBody) *Node { - data := &MethodDeclaration{} - data.modifiers = modifiers - data.AsteriskToken = asteriskToken - data.name = name - data.PostfixToken = postfixToken - data.TypeParameters = typeParameters - data.Parameters = parameters - data.Type = typeNode - data.FullSignature = fullSignature - data.Body = body + data := newData[MethodDeclaration](f) + data.modifiers.set(modifiers) + data.asteriskToken.set(asteriskToken) + data.name.set(name) + data.postfixToken.set(postfixToken) + data.typeParameters.set(typeParameters) + data.parameters.set(parameters) + data.typeNode.set(typeNode) + data.fullSignature.set(fullSignature) + data.body.set(body) return f.newNode(KindMethodDeclaration, data) } func (f *NodeFactory) UpdateMethodDeclaration(node *MethodDeclaration, modifiers *ModifierList, asteriskToken *AsteriskToken, name *PropertyName, postfixToken *TokenNode, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode, fullSignature *TypeNode, body *FunctionBody) *Node { - if modifiers != node.modifiers || asteriskToken != node.AsteriskToken || name != node.name || postfixToken != node.PostfixToken || typeParameters != node.TypeParameters || parameters != node.Parameters || typeNode != node.Type || fullSignature != node.FullSignature || body != node.Body { + if modifiers != node.modifiers.get() || asteriskToken != node.AsteriskToken() || name != node.name.get() || postfixToken != node.PostfixToken() || typeParameters != node.TypeParameters() || parameters != node.Parameters() || typeNode != node.Type() || fullSignature != node.FullSignature() || body != node.Body() { return updateNode(f.NewMethodDeclaration(modifiers, asteriskToken, name, postfixToken, typeParameters, parameters, typeNode, fullSignature, body), node.AsNode(), f.hooks) } return node.AsNode() } func (node *MethodDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.AsteriskToken) || - visit(v, node.name) || - visit(v, node.PostfixToken) || - visitNodeList(v, node.TypeParameters) || - visitNodeList(v, node.Parameters) || - visit(v, node.Type) || - visit(v, node.FullSignature) || - visit(v, node.Body) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.AsteriskToken()) || + visit(v, node.name.get()) || + visit(v, node.PostfixToken()) || + visitNodeList(v, node.TypeParameters()) || + visitNodeList(v, node.Parameters()) || + visit(v, node.Type()) || + visit(v, node.FullSignature()) || + visit(v, node.Body()) } func (node *MethodDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateMethodDeclaration(node, v.visitModifiers(node.modifiers), v.visitNode(node.AsteriskToken), v.visitNode(node.name), v.visitNode(node.PostfixToken), v.visitNodes(node.TypeParameters), v.visitParameters(node.Parameters), v.visitNode(node.Type), v.visitNode(node.FullSignature), v.visitFunctionBody(node.Body)) + return v.Factory.UpdateMethodDeclaration(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.AsteriskToken()), v.visitNode(node.name.get()), v.visitNode(node.PostfixToken()), v.visitNodes(node.TypeParameters()), v.visitParameters(node.Parameters()), v.visitNode(node.Type()), v.visitNode(node.FullSignature()), v.visitFunctionBody(node.Body())) } func (node *MethodDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewMethodDeclaration(node.Modifiers(), node.AsteriskToken, node.name, node.PostfixToken, node.TypeParameters, node.Parameters, node.Type, node.FullSignature, node.Body), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewMethodDeclaration(node.Modifiers(), node.AsteriskToken(), node.name.get(), node.PostfixToken(), node.TypeParameters(), node.Parameters(), node.Type(), node.FullSignature(), node.Body()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *MethodDeclaration) Name() *DeclarationName { - return node.name + return node.name.get() } func IsMethodDeclaration(node *Node) bool { @@ -3375,45 +3755,55 @@ type PropertySignatureDeclaration struct { NodeBase DeclarationBase NamedMemberBase - Type *TypeNode - Initializer *Expression + typeNode link[Node] // *TypeNode + initializer link[Node] // *Expression +} + +func (node *PropertySignatureDeclaration) Type() *TypeNode { return node.typeNode.get() } + +func (node *PropertySignatureDeclaration) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + +func (node *PropertySignatureDeclaration) Initializer() *Expression { return node.initializer.get() } + +func (node *PropertySignatureDeclaration) SetInitializer(initializer *Expression) { + node.initializer.set(initializer) } func (f *NodeFactory) NewPropertySignatureDeclaration(modifiers *ModifierList, name *PropertyName, postfixToken *TokenNode, typeNode *TypeNode, initializer *Expression) *Node { - data := f.propertySignatureDeclarationArena.New() - data.modifiers = modifiers - data.name = name - data.PostfixToken = postfixToken - data.Type = typeNode - data.Initializer = initializer + data := newData[PropertySignatureDeclaration](f) + data.modifiers.set(modifiers) + data.name.set(name) + data.postfixToken.set(postfixToken) + data.typeNode.set(typeNode) + data.initializer.set(initializer) return f.newNode(KindPropertySignature, data) } func (f *NodeFactory) UpdatePropertySignatureDeclaration(node *PropertySignatureDeclaration, modifiers *ModifierList, name *PropertyName, postfixToken *TokenNode, typeNode *TypeNode, initializer *Expression) *Node { - if modifiers != node.modifiers || name != node.name || postfixToken != node.PostfixToken || typeNode != node.Type || initializer != node.Initializer { + if modifiers != node.modifiers.get() || name != node.name.get() || postfixToken != node.PostfixToken() || typeNode != node.Type() || initializer != node.Initializer() { return updateNode(f.NewPropertySignatureDeclaration(modifiers, name, postfixToken, typeNode, initializer), node.AsNode(), f.hooks) } return node.AsNode() } func (node *PropertySignatureDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.name) || - visit(v, node.PostfixToken) || - visit(v, node.Type) || - visit(v, node.Initializer) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.name.get()) || + visit(v, node.PostfixToken()) || + visit(v, node.Type()) || + visit(v, node.Initializer()) } func (node *PropertySignatureDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdatePropertySignatureDeclaration(node, v.visitModifiers(node.modifiers), v.visitNode(node.name), v.visitNode(node.PostfixToken), v.visitNode(node.Type), v.visitNode(node.Initializer)) + return v.Factory.UpdatePropertySignatureDeclaration(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.name.get()), v.visitNode(node.PostfixToken()), v.visitNode(node.Type()), v.visitNode(node.Initializer())) } func (node *PropertySignatureDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewPropertySignatureDeclaration(node.Modifiers(), node.name, node.PostfixToken, node.Type, node.Initializer), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewPropertySignatureDeclaration(node.Modifiers(), node.name.get(), node.PostfixToken(), node.Type(), node.Initializer()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *PropertySignatureDeclaration) Name() *DeclarationName { - return node.name + return node.name.get() } func IsPropertySignatureDeclaration(node *Node) bool { @@ -3430,45 +3820,55 @@ type PropertyDeclaration struct { DeclarationBase NamedMemberBase CompositeBase - Type *TypeNode // Optional - Initializer *Expression // Optional + typeNode link[Node] // *TypeNode. Optional + initializer link[Node] // *Expression. Optional +} + +func (node *PropertyDeclaration) Type() *TypeNode { return node.typeNode.get() } + +func (node *PropertyDeclaration) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + +func (node *PropertyDeclaration) Initializer() *Expression { return node.initializer.get() } + +func (node *PropertyDeclaration) SetInitializer(initializer *Expression) { + node.initializer.set(initializer) } func (f *NodeFactory) NewPropertyDeclaration(modifiers *ModifierList, name *PropertyName, postfixToken *TokenNode, typeNode *TypeNode, initializer *Expression) *Node { - data := &PropertyDeclaration{} - data.modifiers = modifiers - data.name = name - data.PostfixToken = postfixToken - data.Type = typeNode - data.Initializer = initializer + data := newData[PropertyDeclaration](f) + data.modifiers.set(modifiers) + data.name.set(name) + data.postfixToken.set(postfixToken) + data.typeNode.set(typeNode) + data.initializer.set(initializer) return f.newNode(KindPropertyDeclaration, data) } func (f *NodeFactory) UpdatePropertyDeclaration(node *PropertyDeclaration, modifiers *ModifierList, name *PropertyName, postfixToken *TokenNode, typeNode *TypeNode, initializer *Expression) *Node { - if modifiers != node.modifiers || name != node.name || postfixToken != node.PostfixToken || typeNode != node.Type || initializer != node.Initializer { + if modifiers != node.modifiers.get() || name != node.name.get() || postfixToken != node.PostfixToken() || typeNode != node.Type() || initializer != node.Initializer() { return updateNode(f.NewPropertyDeclaration(modifiers, name, postfixToken, typeNode, initializer), node.AsNode(), f.hooks) } return node.AsNode() } func (node *PropertyDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.name) || - visit(v, node.PostfixToken) || - visit(v, node.Type) || - visit(v, node.Initializer) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.name.get()) || + visit(v, node.PostfixToken()) || + visit(v, node.Type()) || + visit(v, node.Initializer()) } func (node *PropertyDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdatePropertyDeclaration(node, v.visitModifiers(node.modifiers), v.visitNode(node.name), v.visitNode(node.PostfixToken), v.visitNode(node.Type), v.visitNode(node.Initializer)) + return v.Factory.UpdatePropertyDeclaration(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.name.get()), v.visitNode(node.PostfixToken()), v.visitNode(node.Type()), v.visitNode(node.Initializer())) } func (node *PropertyDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewPropertyDeclaration(node.Modifiers(), node.name, node.PostfixToken, node.Type, node.Initializer), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewPropertyDeclaration(node.Modifiers(), node.name.get(), node.PostfixToken(), node.Type(), node.Initializer()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *PropertyDeclaration) Name() *DeclarationName { - return node.name + return node.name.get() } func IsPropertyDeclaration(node *Node) bool { @@ -3486,7 +3886,7 @@ type SemicolonClassElement struct { } func (f *NodeFactory) NewSemicolonClassElement() *Node { - data := &SemicolonClassElement{} + data := newData[SemicolonClassElement](f) return f.newNode(KindSemicolonClassElement, data) } @@ -3509,34 +3909,38 @@ type ClassStaticBlockDeclaration struct { ModifiersBase LocalsContainerBase CompositeBase - Body *BlockNode + body link[Node] // *BlockNode ReturnFlowNode *FlowNode } +func (node *ClassStaticBlockDeclaration) Body() *BlockNode { return node.body.get() } + +func (node *ClassStaticBlockDeclaration) SetBody(body *BlockNode) { node.body.set(body) } + func (f *NodeFactory) NewClassStaticBlockDeclaration(modifiers *ModifierList, body *BlockNode) *Node { - data := &ClassStaticBlockDeclaration{} - data.modifiers = modifiers - data.Body = body + data := newData[ClassStaticBlockDeclaration](f) + data.modifiers.set(modifiers) + data.body.set(body) return f.newNode(KindClassStaticBlockDeclaration, data) } func (f *NodeFactory) UpdateClassStaticBlockDeclaration(node *ClassStaticBlockDeclaration, modifiers *ModifierList, body *BlockNode) *Node { - if modifiers != node.modifiers || body != node.Body { + if modifiers != node.modifiers.get() || body != node.Body() { return updateNode(f.NewClassStaticBlockDeclaration(modifiers, body), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ClassStaticBlockDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || visit(v, node.Body) + return visitModifiers(v, node.modifiers.get()) || visit(v, node.Body()) } func (node *ClassStaticBlockDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateClassStaticBlockDeclaration(node, v.visitModifiers(node.modifiers), v.visitNode(node.Body)) + return v.Factory.UpdateClassStaticBlockDeclaration(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.Body())) } func (node *ClassStaticBlockDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewClassStaticBlockDeclaration(node.Modifiers(), node.Body), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewClassStaticBlockDeclaration(node.Modifiers(), node.Body()), node.AsNode(), f.AsNodeFactory().hooks) } func IsClassStaticBlockDeclaration(node *Node) bool { @@ -3552,7 +3956,7 @@ type OmittedExpression struct { } func (f *NodeFactory) NewOmittedExpression() *Node { - data := &OmittedExpression{} + data := newData[OmittedExpression](f) return f.newNode(KindOmittedExpression, data) } @@ -3574,7 +3978,7 @@ type KeywordExpression struct { } func (f *NodeFactory) NewKeywordExpression(kind KeywordExpressionSyntaxKind) *Node { - data := f.keywordExpressionArena.New() + data := newData[KeywordExpression](f) return f.newNode(kind, data) } @@ -3599,8 +4003,9 @@ type StringLiteral struct { } func (f *NodeFactory) NewStringLiteral(text string, tokenFlags TokenFlags) *Node { - data := f.stringLiteralArena.New() + data := newData[StringLiteral](f) data.Text = text + f.keepString(text) data.TokenFlags = tokenFlags & TokenFlagsStringLiteralFlags f.textCount++ return f.newNode(KindStringLiteral, data) @@ -3623,8 +4028,9 @@ type NumericLiteral struct { } func (f *NodeFactory) NewNumericLiteral(text string, tokenFlags TokenFlags) *Node { - data := f.numericLiteralArena.New() + data := newData[NumericLiteral](f) data.Text = text + f.keepString(text) data.TokenFlags = tokenFlags & TokenFlagsNumericLiteralFlags f.textCount++ return f.newNode(KindNumericLiteral, data) @@ -3647,8 +4053,9 @@ type BigIntLiteral struct { } func (f *NodeFactory) NewBigIntLiteral(text string, tokenFlags TokenFlags) *Node { - data := &BigIntLiteral{} + data := newData[BigIntLiteral](f) data.Text = text + f.keepString(text) data.TokenFlags = tokenFlags & TokenFlagsNumericLiteralFlags f.textCount++ return f.newNode(KindBigIntLiteral, data) @@ -3671,8 +4078,9 @@ type RegularExpressionLiteral struct { } func (f *NodeFactory) NewRegularExpressionLiteral(text string, tokenFlags TokenFlags) *Node { - data := &RegularExpressionLiteral{} + data := newData[RegularExpressionLiteral](f) data.Text = text + f.keepString(text) data.TokenFlags = tokenFlags & TokenFlagsRegularExpressionLiteralFlags f.textCount++ return f.newNode(KindRegularExpressionLiteral, data) @@ -3697,8 +4105,9 @@ type NoSubstitutionTemplateLiteral struct { } func (f *NodeFactory) NewNoSubstitutionTemplateLiteral(text string, templateFlags TokenFlags) *Node { - data := &NoSubstitutionTemplateLiteral{} + data := newData[NoSubstitutionTemplateLiteral](f) data.Text = text + f.keepString(text) data.TemplateFlags = templateFlags & TokenFlagsTemplateLiteralLikeFlags f.textCount++ return f.newNode(KindNoSubstitutionTemplateLiteral, data) @@ -3721,43 +4130,61 @@ type BinaryExpression struct { DeclarationBase ModifiersBase CompositeBase - Left *Expression - Type *TypeNode // Optional - OperatorToken *BinaryOperatorToken - Right *Expression + left link[Node] // *Expression + typeNode link[Node] // *TypeNode. Optional + operatorToken link[Node] // *BinaryOperatorToken + right link[Node] // *Expression +} + +func (node *BinaryExpression) Left() *Expression { return node.left.get() } + +func (node *BinaryExpression) SetLeft(left *Expression) { node.left.set(left) } + +func (node *BinaryExpression) Type() *TypeNode { return node.typeNode.get() } + +func (node *BinaryExpression) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + +func (node *BinaryExpression) OperatorToken() *BinaryOperatorToken { return node.operatorToken.get() } + +func (node *BinaryExpression) SetOperatorToken(operatorToken *BinaryOperatorToken) { + node.operatorToken.set(operatorToken) } +func (node *BinaryExpression) Right() *Expression { return node.right.get() } + +func (node *BinaryExpression) SetRight(right *Expression) { node.right.set(right) } + func (f *NodeFactory) NewBinaryExpression(modifiers *ModifierList, left *Expression, typeNode *TypeNode, operatorToken *BinaryOperatorToken, right *Expression) *Node { - data := f.binaryExpressionArena.New() - data.modifiers = modifiers - data.Left = left - data.Type = typeNode - data.OperatorToken = operatorToken - data.Right = right + data := newData[BinaryExpression](f) + data.modifiers.set(modifiers) + data.left.set(left) + data.typeNode.set(typeNode) + data.operatorToken.set(operatorToken) + data.right.set(right) return f.newNode(KindBinaryExpression, data) } func (f *NodeFactory) UpdateBinaryExpression(node *BinaryExpression, modifiers *ModifierList, left *Expression, typeNode *TypeNode, operatorToken *BinaryOperatorToken, right *Expression) *Node { - if modifiers != node.modifiers || left != node.Left || typeNode != node.Type || operatorToken != node.OperatorToken || right != node.Right { + if modifiers != node.modifiers.get() || left != node.Left() || typeNode != node.Type() || operatorToken != node.OperatorToken() || right != node.Right() { return updateNode(f.NewBinaryExpression(modifiers, left, typeNode, operatorToken, right), node.AsNode(), f.hooks) } return node.AsNode() } func (node *BinaryExpression) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.Left) || - visit(v, node.Type) || - visit(v, node.OperatorToken) || - visit(v, node.Right) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.Left()) || + visit(v, node.Type()) || + visit(v, node.OperatorToken()) || + visit(v, node.Right()) } func (node *BinaryExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateBinaryExpression(node, v.visitModifiers(node.modifiers), v.visitNode(node.Left), v.visitNode(node.Type), v.visitNode(node.OperatorToken), v.visitNode(node.Right)) + return v.Factory.UpdateBinaryExpression(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.Left()), v.visitNode(node.Type()), v.visitNode(node.OperatorToken()), v.visitNode(node.Right())) } func (node *BinaryExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewBinaryExpression(node.Modifiers(), node.Left, node.Type, node.OperatorToken, node.Right), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewBinaryExpression(node.Modifiers(), node.Left(), node.Type(), node.OperatorToken(), node.Right()), node.AsNode(), f.AsNodeFactory().hooks) } func IsBinaryExpression(node *Node) bool { @@ -3771,37 +4198,41 @@ func IsBinaryExpression(node *Node) bool { type PrefixUnaryExpression struct { UpdateExpressionBase Operator Kind - Operand *Expression + operand link[Node] // *Expression } +func (node *PrefixUnaryExpression) Operand() *Expression { return node.operand.get() } + +func (node *PrefixUnaryExpression) SetOperand(operand *Expression) { node.operand.set(operand) } + func (f *NodeFactory) NewPrefixUnaryExpression(operator Kind, operand *Expression) *Node { - data := f.prefixUnaryExpressionArena.New() + data := newData[PrefixUnaryExpression](f) data.Operator = operator - data.Operand = operand + data.operand.set(operand) return f.newNode(KindPrefixUnaryExpression, data) } func (f *NodeFactory) UpdatePrefixUnaryExpression(node *PrefixUnaryExpression, operator Kind, operand *Expression) *Node { - if operator != node.Operator || operand != node.Operand { + if operator != node.Operator || operand != node.Operand() { return updateNode(f.NewPrefixUnaryExpression(operator, operand), node.AsNode(), f.hooks) } return node.AsNode() } func (node *PrefixUnaryExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Operand) + return visit(v, node.Operand()) } func (node *PrefixUnaryExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdatePrefixUnaryExpression(node, node.Operator, v.visitNode(node.Operand)) + return v.Factory.UpdatePrefixUnaryExpression(node, node.Operator, v.visitNode(node.Operand())) } func (node *PrefixUnaryExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewPrefixUnaryExpression(node.Operator, node.Operand), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewPrefixUnaryExpression(node.Operator, node.Operand()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *PrefixUnaryExpression) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Operand) + return propagateSubtreeFacts(node.Operand()) } func IsPrefixUnaryExpression(node *Node) bool { @@ -3814,38 +4245,42 @@ func IsPrefixUnaryExpression(node *Node) bool { type PostfixUnaryExpression struct { UpdateExpressionBase - Operand *Expression + operand link[Node] // *Expression Operator Kind } +func (node *PostfixUnaryExpression) Operand() *Expression { return node.operand.get() } + +func (node *PostfixUnaryExpression) SetOperand(operand *Expression) { node.operand.set(operand) } + func (f *NodeFactory) NewPostfixUnaryExpression(operand *Expression, operator Kind) *Node { - data := &PostfixUnaryExpression{} - data.Operand = operand + data := newData[PostfixUnaryExpression](f) + data.operand.set(operand) data.Operator = operator return f.newNode(KindPostfixUnaryExpression, data) } func (f *NodeFactory) UpdatePostfixUnaryExpression(node *PostfixUnaryExpression, operand *Expression, operator Kind) *Node { - if operand != node.Operand || operator != node.Operator { + if operand != node.Operand() || operator != node.Operator { return updateNode(f.NewPostfixUnaryExpression(operand, operator), node.AsNode(), f.hooks) } return node.AsNode() } func (node *PostfixUnaryExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Operand) + return visit(v, node.Operand()) } func (node *PostfixUnaryExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdatePostfixUnaryExpression(node, v.visitNode(node.Operand), node.Operator) + return v.Factory.UpdatePostfixUnaryExpression(node, v.visitNode(node.Operand()), node.Operator) } func (node *PostfixUnaryExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewPostfixUnaryExpression(node.Operand, node.Operator), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewPostfixUnaryExpression(node.Operand(), node.Operator), node.AsNode(), f.AsNodeFactory().hooks) } func (node *PostfixUnaryExpression) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Operand) + return propagateSubtreeFacts(node.Operand()) } func IsPostfixUnaryExpression(node *Node) bool { @@ -3858,34 +4293,44 @@ func IsPostfixUnaryExpression(node *Node) bool { type YieldExpression struct { ExpressionBase - AsteriskToken *AsteriskToken // Optional - Expression *Expression // Optional + asteriskToken link[Node] // *AsteriskToken. Optional + expression link[Node] // *Expression. Optional } -func (f *NodeFactory) NewYieldExpression(asteriskToken *AsteriskToken, expression *Expression) *Node { - data := &YieldExpression{} - data.AsteriskToken = asteriskToken - data.Expression = expression - return f.newNode(KindYieldExpression, data) +func (node *YieldExpression) AsteriskToken() *AsteriskToken { return node.asteriskToken.get() } + +func (node *YieldExpression) SetAsteriskToken(asteriskToken *AsteriskToken) { + node.asteriskToken.set(asteriskToken) +} + +func (node *YieldExpression) Expression() *Expression { return node.expression.get() } + +func (node *YieldExpression) SetExpression(expression *Expression) { node.expression.set(expression) } + +func (f *NodeFactory) NewYieldExpression(asteriskToken *AsteriskToken, expression *Expression) *Node { + data := newData[YieldExpression](f) + data.asteriskToken.set(asteriskToken) + data.expression.set(expression) + return f.newNode(KindYieldExpression, data) } func (f *NodeFactory) UpdateYieldExpression(node *YieldExpression, asteriskToken *AsteriskToken, expression *Expression) *Node { - if asteriskToken != node.AsteriskToken || expression != node.Expression { + if asteriskToken != node.AsteriskToken() || expression != node.Expression() { return updateNode(f.NewYieldExpression(asteriskToken, expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *YieldExpression) ForEachChild(v Visitor) bool { - return visit(v, node.AsteriskToken) || visit(v, node.Expression) + return visit(v, node.AsteriskToken()) || visit(v, node.Expression()) } func (node *YieldExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateYieldExpression(node, v.visitNode(node.AsteriskToken), v.visitNode(node.Expression)) + return v.Factory.UpdateYieldExpression(node, v.visitNode(node.AsteriskToken()), v.visitNode(node.Expression())) } func (node *YieldExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewYieldExpression(node.AsteriskToken, node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewYieldExpression(node.AsteriskToken(), node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func IsYieldExpression(node *Node) bool { @@ -3903,44 +4348,52 @@ type ArrowFunction struct { FunctionLikeWithBodyBase FlowNodeBase CompositeBase - EqualsGreaterThanToken *EqualsGreaterThanToken + equalsGreaterThanToken link[Node] // *EqualsGreaterThanToken +} + +func (node *ArrowFunction) EqualsGreaterThanToken() *EqualsGreaterThanToken { + return node.equalsGreaterThanToken.get() +} + +func (node *ArrowFunction) SetEqualsGreaterThanToken(equalsGreaterThanToken *EqualsGreaterThanToken) { + node.equalsGreaterThanToken.set(equalsGreaterThanToken) } func (f *NodeFactory) NewArrowFunction(modifiers *ModifierList, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode, fullSignature *TypeNode, equalsGreaterThanToken *EqualsGreaterThanToken, body *ConciseBody) *Node { - data := &ArrowFunction{} - data.modifiers = modifiers - data.TypeParameters = typeParameters - data.Parameters = parameters - data.Type = typeNode - data.FullSignature = fullSignature - data.EqualsGreaterThanToken = equalsGreaterThanToken - data.Body = body + data := newData[ArrowFunction](f) + data.modifiers.set(modifiers) + data.typeParameters.set(typeParameters) + data.parameters.set(parameters) + data.typeNode.set(typeNode) + data.fullSignature.set(fullSignature) + data.equalsGreaterThanToken.set(equalsGreaterThanToken) + data.body.set(body) return f.newNode(KindArrowFunction, data) } func (f *NodeFactory) UpdateArrowFunction(node *ArrowFunction, modifiers *ModifierList, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode, fullSignature *TypeNode, equalsGreaterThanToken *EqualsGreaterThanToken, body *ConciseBody) *Node { - if modifiers != node.modifiers || typeParameters != node.TypeParameters || parameters != node.Parameters || typeNode != node.Type || fullSignature != node.FullSignature || equalsGreaterThanToken != node.EqualsGreaterThanToken || body != node.Body { + if modifiers != node.modifiers.get() || typeParameters != node.TypeParameters() || parameters != node.Parameters() || typeNode != node.Type() || fullSignature != node.FullSignature() || equalsGreaterThanToken != node.EqualsGreaterThanToken() || body != node.Body() { return updateNode(f.NewArrowFunction(modifiers, typeParameters, parameters, typeNode, fullSignature, equalsGreaterThanToken, body), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ArrowFunction) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visitNodeList(v, node.TypeParameters) || - visitNodeList(v, node.Parameters) || - visit(v, node.Type) || - visit(v, node.FullSignature) || - visit(v, node.EqualsGreaterThanToken) || - visit(v, node.Body) + return visitModifiers(v, node.modifiers.get()) || + visitNodeList(v, node.TypeParameters()) || + visitNodeList(v, node.Parameters()) || + visit(v, node.Type()) || + visit(v, node.FullSignature()) || + visit(v, node.EqualsGreaterThanToken()) || + visit(v, node.Body()) } func (node *ArrowFunction) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateArrowFunction(node, v.visitModifiers(node.modifiers), v.visitNodes(node.TypeParameters), v.visitParameters(node.Parameters), v.visitNode(node.Type), v.visitNode(node.FullSignature), v.visitNode(node.EqualsGreaterThanToken), v.visitFunctionBody(node.Body)) + return v.Factory.UpdateArrowFunction(node, v.visitModifiers(node.modifiers.get()), v.visitNodes(node.TypeParameters()), v.visitParameters(node.Parameters()), v.visitNode(node.Type()), v.visitNode(node.FullSignature()), v.visitNode(node.EqualsGreaterThanToken()), v.visitFunctionBody(node.Body())) } func (node *ArrowFunction) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewArrowFunction(node.Modifiers(), node.TypeParameters, node.Parameters, node.Type, node.FullSignature, node.EqualsGreaterThanToken, node.Body), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewArrowFunction(node.Modifiers(), node.TypeParameters(), node.Parameters(), node.Type(), node.FullSignature(), node.EqualsGreaterThanToken(), node.Body()), node.AsNode(), f.AsNodeFactory().hooks) } func IsArrowFunction(node *Node) bool { @@ -3958,51 +4411,51 @@ type FunctionExpression struct { FunctionLikeWithBodyBase FlowNodeBase CompositeBase - name *IdentifierNode // Optional + name link[Node] // *IdentifierNode. Optional ReturnFlowNode *FlowNode } func (f *NodeFactory) NewFunctionExpression(modifiers *ModifierList, asteriskToken *AsteriskToken, name *IdentifierNode, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode, fullSignature *TypeNode, body *FunctionBody) *Node { - data := &FunctionExpression{} - data.modifiers = modifiers - data.AsteriskToken = asteriskToken - data.name = name - data.TypeParameters = typeParameters - data.Parameters = parameters - data.Type = typeNode - data.FullSignature = fullSignature - data.Body = body + data := newData[FunctionExpression](f) + data.modifiers.set(modifiers) + data.asteriskToken.set(asteriskToken) + data.name.set(name) + data.typeParameters.set(typeParameters) + data.parameters.set(parameters) + data.typeNode.set(typeNode) + data.fullSignature.set(fullSignature) + data.body.set(body) return f.newNode(KindFunctionExpression, data) } func (f *NodeFactory) UpdateFunctionExpression(node *FunctionExpression, modifiers *ModifierList, asteriskToken *AsteriskToken, name *IdentifierNode, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode, fullSignature *TypeNode, body *FunctionBody) *Node { - if modifiers != node.modifiers || asteriskToken != node.AsteriskToken || name != node.name || typeParameters != node.TypeParameters || parameters != node.Parameters || typeNode != node.Type || fullSignature != node.FullSignature || body != node.Body { + if modifiers != node.modifiers.get() || asteriskToken != node.AsteriskToken() || name != node.name.get() || typeParameters != node.TypeParameters() || parameters != node.Parameters() || typeNode != node.Type() || fullSignature != node.FullSignature() || body != node.Body() { return updateNode(f.NewFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, typeNode, fullSignature, body), node.AsNode(), f.hooks) } return node.AsNode() } func (node *FunctionExpression) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.AsteriskToken) || - visit(v, node.name) || - visitNodeList(v, node.TypeParameters) || - visitNodeList(v, node.Parameters) || - visit(v, node.Type) || - visit(v, node.FullSignature) || - visit(v, node.Body) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.AsteriskToken()) || + visit(v, node.name.get()) || + visitNodeList(v, node.TypeParameters()) || + visitNodeList(v, node.Parameters()) || + visit(v, node.Type()) || + visit(v, node.FullSignature()) || + visit(v, node.Body()) } func (node *FunctionExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateFunctionExpression(node, v.visitModifiers(node.modifiers), v.visitNode(node.AsteriskToken), v.visitNode(node.name), v.visitNodes(node.TypeParameters), v.visitParameters(node.Parameters), v.visitNode(node.Type), v.visitNode(node.FullSignature), v.visitFunctionBody(node.Body)) + return v.Factory.UpdateFunctionExpression(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.AsteriskToken()), v.visitNode(node.name.get()), v.visitNodes(node.TypeParameters()), v.visitParameters(node.Parameters()), v.visitNode(node.Type()), v.visitNode(node.FullSignature()), v.visitFunctionBody(node.Body())) } func (node *FunctionExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewFunctionExpression(node.Modifiers(), node.AsteriskToken, node.name, node.TypeParameters, node.Parameters, node.Type, node.FullSignature, node.Body), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewFunctionExpression(node.Modifiers(), node.AsteriskToken(), node.name.get(), node.TypeParameters(), node.Parameters(), node.Type(), node.FullSignature(), node.Body()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *FunctionExpression) Name() *DeclarationName { - return node.name + return node.name.get() } func IsFunctionExpression(node *Node) bool { @@ -4015,34 +4468,42 @@ func IsFunctionExpression(node *Node) bool { type AsExpression struct { ExpressionBase - Expression *Expression - Type *TypeNode + expression link[Node] // *Expression + typeNode link[Node] // *TypeNode } +func (node *AsExpression) Expression() *Expression { return node.expression.get() } + +func (node *AsExpression) SetExpression(expression *Expression) { node.expression.set(expression) } + +func (node *AsExpression) Type() *TypeNode { return node.typeNode.get() } + +func (node *AsExpression) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + func (f *NodeFactory) NewAsExpression(expression *Expression, typeNode *TypeNode) *Node { - data := &AsExpression{} - data.Expression = expression - data.Type = typeNode + data := newData[AsExpression](f) + data.expression.set(expression) + data.typeNode.set(typeNode) return f.newNode(KindAsExpression, data) } func (f *NodeFactory) UpdateAsExpression(node *AsExpression, expression *Expression, typeNode *TypeNode) *Node { - if expression != node.Expression || typeNode != node.Type { + if expression != node.Expression() || typeNode != node.Type() { return updateNode(f.NewAsExpression(expression, typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *AsExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) || visit(v, node.Type) + return visit(v, node.Expression()) || visit(v, node.Type()) } func (node *AsExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateAsExpression(node, v.visitNode(node.Expression), v.visitNode(node.Type)) + return v.Factory.UpdateAsExpression(node, v.visitNode(node.Expression()), v.visitNode(node.Type())) } func (node *AsExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewAsExpression(node.Expression, node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewAsExpression(node.Expression(), node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func IsAsExpression(node *Node) bool { @@ -4055,34 +4516,44 @@ func IsAsExpression(node *Node) bool { type SatisfiesExpression struct { ExpressionBase - Expression *Expression - Type *TypeNode + expression link[Node] // *Expression + typeNode link[Node] // *TypeNode +} + +func (node *SatisfiesExpression) Expression() *Expression { return node.expression.get() } + +func (node *SatisfiesExpression) SetExpression(expression *Expression) { + node.expression.set(expression) } +func (node *SatisfiesExpression) Type() *TypeNode { return node.typeNode.get() } + +func (node *SatisfiesExpression) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + func (f *NodeFactory) NewSatisfiesExpression(expression *Expression, typeNode *TypeNode) *Node { - data := &SatisfiesExpression{} - data.Expression = expression - data.Type = typeNode + data := newData[SatisfiesExpression](f) + data.expression.set(expression) + data.typeNode.set(typeNode) return f.newNode(KindSatisfiesExpression, data) } func (f *NodeFactory) UpdateSatisfiesExpression(node *SatisfiesExpression, expression *Expression, typeNode *TypeNode) *Node { - if expression != node.Expression || typeNode != node.Type { + if expression != node.Expression() || typeNode != node.Type() { return updateNode(f.NewSatisfiesExpression(expression, typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *SatisfiesExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) || visit(v, node.Type) + return visit(v, node.Expression()) || visit(v, node.Type()) } func (node *SatisfiesExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateSatisfiesExpression(node, v.visitNode(node.Expression), v.visitNode(node.Type)) + return v.Factory.UpdateSatisfiesExpression(node, v.visitNode(node.Expression()), v.visitNode(node.Type())) } func (node *SatisfiesExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewSatisfiesExpression(node.Expression, node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewSatisfiesExpression(node.Expression(), node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func IsSatisfiesExpression(node *Node) bool { @@ -4096,52 +4567,76 @@ func IsSatisfiesExpression(node *Node) bool { type ConditionalExpression struct { ExpressionBase CompositeBase - Condition *Expression - QuestionToken *QuestionToken - WhenTrue *Expression - ColonToken *ColonToken - WhenFalse *Expression + condition link[Node] // *Expression + questionToken link[Node] // *QuestionToken + whenTrue link[Node] // *Expression + colonToken link[Node] // *ColonToken + whenFalse link[Node] // *Expression +} + +func (node *ConditionalExpression) Condition() *Expression { return node.condition.get() } + +func (node *ConditionalExpression) SetCondition(condition *Expression) { node.condition.set(condition) } + +func (node *ConditionalExpression) QuestionToken() *QuestionToken { return node.questionToken.get() } + +func (node *ConditionalExpression) SetQuestionToken(questionToken *QuestionToken) { + node.questionToken.set(questionToken) +} + +func (node *ConditionalExpression) WhenTrue() *Expression { return node.whenTrue.get() } + +func (node *ConditionalExpression) SetWhenTrue(whenTrue *Expression) { node.whenTrue.set(whenTrue) } + +func (node *ConditionalExpression) ColonToken() *ColonToken { return node.colonToken.get() } + +func (node *ConditionalExpression) SetColonToken(colonToken *ColonToken) { + node.colonToken.set(colonToken) } +func (node *ConditionalExpression) WhenFalse() *Expression { return node.whenFalse.get() } + +func (node *ConditionalExpression) SetWhenFalse(whenFalse *Expression) { node.whenFalse.set(whenFalse) } + func (f *NodeFactory) NewConditionalExpression(condition *Expression, questionToken *QuestionToken, whenTrue *Expression, colonToken *ColonToken, whenFalse *Expression) *Node { - data := f.conditionalExpressionArena.New() - data.Condition = condition - data.QuestionToken = questionToken - data.WhenTrue = whenTrue - data.ColonToken = colonToken - data.WhenFalse = whenFalse + data := newData[ConditionalExpression](f) + data.condition.set(condition) + data.questionToken.set(questionToken) + data.whenTrue.set(whenTrue) + data.colonToken.set(colonToken) + data.whenFalse.set(whenFalse) return f.newNode(KindConditionalExpression, data) } func (f *NodeFactory) UpdateConditionalExpression(node *ConditionalExpression, condition *Expression, questionToken *QuestionToken, whenTrue *Expression, colonToken *ColonToken, whenFalse *Expression) *Node { - if condition != node.Condition || questionToken != node.QuestionToken || whenTrue != node.WhenTrue || colonToken != node.ColonToken || whenFalse != node.WhenFalse { + if condition != node.Condition() || questionToken != node.QuestionToken() || whenTrue != node.WhenTrue() || colonToken != node.ColonToken() || whenFalse != node.WhenFalse() { return updateNode(f.NewConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ConditionalExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Condition) || - visit(v, node.QuestionToken) || - visit(v, node.WhenTrue) || - visit(v, node.ColonToken) || - visit(v, node.WhenFalse) + return visit(v, node.Condition()) || + visit(v, node.QuestionToken()) || + visit(v, node.WhenTrue()) || + visit(v, node.ColonToken()) || + visit(v, node.WhenFalse()) } func (node *ConditionalExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateConditionalExpression(node, v.visitNode(node.Condition), v.visitNode(node.QuestionToken), v.visitNode(node.WhenTrue), v.visitNode(node.ColonToken), v.visitNode(node.WhenFalse)) + return v.Factory.UpdateConditionalExpression(node, v.visitNode(node.Condition()), v.visitNode(node.QuestionToken()), v.visitNode(node.WhenTrue()), v.visitNode(node.ColonToken()), v.visitNode(node.WhenFalse())) } func (node *ConditionalExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewConditionalExpression(node.Condition, node.QuestionToken, node.WhenTrue, node.ColonToken, node.WhenFalse), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewConditionalExpression(node.Condition(), node.QuestionToken(), node.WhenTrue(), node.ColonToken(), node.WhenFalse()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ConditionalExpression) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Condition) | - propagateSubtreeFacts(node.QuestionToken) | - propagateSubtreeFacts(node.WhenTrue) | - propagateSubtreeFacts(node.ColonToken) | - propagateSubtreeFacts(node.WhenFalse) + return propagateSubtreeFacts(node.Condition()) | + propagateSubtreeFacts(node.QuestionToken()) | + propagateSubtreeFacts(node.WhenTrue()) | + propagateSubtreeFacts(node.ColonToken()) | + propagateSubtreeFacts(node.WhenFalse()) } func IsConditionalExpression(node *Node) bool { @@ -4156,42 +4651,56 @@ type PropertyAccessExpression struct { MemberExpressionBase FlowNodeBase CompositeBase - Expression *Expression - QuestionDotToken *QuestionDotToken // Optional - name *MemberName + expression link[Node] // *Expression + questionDotToken link[Node] // *QuestionDotToken. Optional + name link[Node] // *MemberName +} + +func (node *PropertyAccessExpression) Expression() *Expression { return node.expression.get() } + +func (node *PropertyAccessExpression) SetExpression(expression *Expression) { + node.expression.set(expression) +} + +func (node *PropertyAccessExpression) QuestionDotToken() *QuestionDotToken { + return node.questionDotToken.get() +} + +func (node *PropertyAccessExpression) SetQuestionDotToken(questionDotToken *QuestionDotToken) { + node.questionDotToken.set(questionDotToken) } func (f *NodeFactory) NewPropertyAccessExpression(expression *Expression, questionDotToken *QuestionDotToken, name *MemberName, flags NodeFlags) *Node { - data := f.propertyAccessExpressionArena.New() - data.Expression = expression - data.QuestionDotToken = questionDotToken - data.name = name + data := newData[PropertyAccessExpression](f) + data.expression.set(expression) + data.questionDotToken.set(questionDotToken) + data.name.set(name) node := f.newNode(KindPropertyAccessExpression, data) node.Flags |= flags & NodeFlagsOptionalChain return node } func (f *NodeFactory) UpdatePropertyAccessExpression(node *PropertyAccessExpression, expression *Expression, questionDotToken *QuestionDotToken, name *MemberName, flags NodeFlags) *Node { - if expression != node.Expression || questionDotToken != node.QuestionDotToken || name != node.name || flags != node.Flags { + if expression != node.Expression() || questionDotToken != node.QuestionDotToken() || name != node.name.get() || flags != node.Flags { return updateNode(f.NewPropertyAccessExpression(expression, questionDotToken, name, flags), node.AsNode(), f.hooks) } return node.AsNode() } func (node *PropertyAccessExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) || visit(v, node.QuestionDotToken) || visit(v, node.name) + return visit(v, node.Expression()) || visit(v, node.QuestionDotToken()) || visit(v, node.name.get()) } func (node *PropertyAccessExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdatePropertyAccessExpression(node, v.visitNode(node.Expression), v.visitNode(node.QuestionDotToken), v.visitNode(node.name), node.Flags) + return v.Factory.UpdatePropertyAccessExpression(node, v.visitNode(node.Expression()), v.visitNode(node.QuestionDotToken()), v.visitNode(node.name.get()), node.Flags) } func (node *PropertyAccessExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewPropertyAccessExpression(node.Expression, node.QuestionDotToken, node.name, node.Flags), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewPropertyAccessExpression(node.Expression(), node.QuestionDotToken(), node.name.get(), node.Flags), node.AsNode(), f.AsNodeFactory().hooks) } func (node *PropertyAccessExpression) Name() *DeclarationName { - return node.name + return node.name.get() } func IsPropertyAccessExpression(node *Node) bool { @@ -4206,44 +4715,66 @@ type ElementAccessExpression struct { MemberExpressionBase FlowNodeBase CompositeBase - Expression *Expression - QuestionDotToken *QuestionDotToken // Optional - ArgumentExpression *Expression + expression link[Node] // *Expression + questionDotToken link[Node] // *QuestionDotToken. Optional + argumentExpression link[Node] // *Expression +} + +func (node *ElementAccessExpression) Expression() *Expression { return node.expression.get() } + +func (node *ElementAccessExpression) SetExpression(expression *Expression) { + node.expression.set(expression) +} + +func (node *ElementAccessExpression) QuestionDotToken() *QuestionDotToken { + return node.questionDotToken.get() +} + +func (node *ElementAccessExpression) SetQuestionDotToken(questionDotToken *QuestionDotToken) { + node.questionDotToken.set(questionDotToken) +} + +func (node *ElementAccessExpression) ArgumentExpression() *Expression { + return node.argumentExpression.get() +} + +func (node *ElementAccessExpression) SetArgumentExpression(argumentExpression *Expression) { + node.argumentExpression.set(argumentExpression) } func (f *NodeFactory) NewElementAccessExpression(expression *Expression, questionDotToken *QuestionDotToken, argumentExpression *Expression, flags NodeFlags) *Node { - data := f.elementAccessExpressionArena.New() - data.Expression = expression - data.QuestionDotToken = questionDotToken - data.ArgumentExpression = argumentExpression + data := newData[ElementAccessExpression](f) + data.expression.set(expression) + data.questionDotToken.set(questionDotToken) + data.argumentExpression.set(argumentExpression) node := f.newNode(KindElementAccessExpression, data) node.Flags |= flags & NodeFlagsOptionalChain return node } func (f *NodeFactory) UpdateElementAccessExpression(node *ElementAccessExpression, expression *Expression, questionDotToken *QuestionDotToken, argumentExpression *Expression, flags NodeFlags) *Node { - if expression != node.Expression || questionDotToken != node.QuestionDotToken || argumentExpression != node.ArgumentExpression || flags != node.Flags { + if expression != node.Expression() || questionDotToken != node.QuestionDotToken() || argumentExpression != node.ArgumentExpression() || flags != node.Flags { return updateNode(f.NewElementAccessExpression(expression, questionDotToken, argumentExpression, flags), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ElementAccessExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) || visit(v, node.QuestionDotToken) || visit(v, node.ArgumentExpression) + return visit(v, node.Expression()) || visit(v, node.QuestionDotToken()) || visit(v, node.ArgumentExpression()) } func (node *ElementAccessExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateElementAccessExpression(node, v.visitNode(node.Expression), v.visitNode(node.QuestionDotToken), v.visitNode(node.ArgumentExpression), node.Flags) + return v.Factory.UpdateElementAccessExpression(node, v.visitNode(node.Expression()), v.visitNode(node.QuestionDotToken()), v.visitNode(node.ArgumentExpression()), node.Flags) } func (node *ElementAccessExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewElementAccessExpression(node.Expression, node.QuestionDotToken, node.ArgumentExpression, node.Flags), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewElementAccessExpression(node.Expression(), node.QuestionDotToken(), node.ArgumentExpression(), node.Flags), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ElementAccessExpression) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | - propagateSubtreeFacts(node.QuestionDotToken) | - propagateSubtreeFacts(node.ArgumentExpression) + return propagateSubtreeFacts(node.Expression()) | + propagateSubtreeFacts(node.QuestionDotToken()) | + propagateSubtreeFacts(node.ArgumentExpression()) } func IsElementAccessExpression(node *Node) bool { @@ -4258,43 +4789,63 @@ type CallExpression struct { LeftHandSideExpressionBase DeclarationBase CompositeBase - Expression *Expression - QuestionDotToken *QuestionDotToken // Optional - TypeArguments *TypeList // Optional - Arguments *ElementList + expression link[Node] // *Expression + questionDotToken link[Node] // *QuestionDotToken. Optional + typeArguments link[NodeList] // *TypeList. Optional + arguments link[NodeList] // *ElementList } +func (node *CallExpression) Expression() *Expression { return node.expression.get() } + +func (node *CallExpression) SetExpression(expression *Expression) { node.expression.set(expression) } + +func (node *CallExpression) QuestionDotToken() *QuestionDotToken { return node.questionDotToken.get() } + +func (node *CallExpression) SetQuestionDotToken(questionDotToken *QuestionDotToken) { + node.questionDotToken.set(questionDotToken) +} + +func (node *CallExpression) TypeArguments() *TypeList { return node.typeArguments.get() } + +func (node *CallExpression) SetTypeArguments(typeArguments *TypeList) { + node.typeArguments.set(typeArguments) +} + +func (node *CallExpression) Arguments() *ElementList { return node.arguments.get() } + +func (node *CallExpression) SetArguments(arguments *ElementList) { node.arguments.set(arguments) } + func (f *NodeFactory) NewCallExpression(expression *Expression, questionDotToken *QuestionDotToken, typeArguments *TypeList, arguments *ElementList, flags NodeFlags) *Node { - data := f.callExpressionArena.New() - data.Expression = expression - data.QuestionDotToken = questionDotToken - data.TypeArguments = typeArguments - data.Arguments = arguments + data := newData[CallExpression](f) + data.expression.set(expression) + data.questionDotToken.set(questionDotToken) + data.typeArguments.set(typeArguments) + data.arguments.set(arguments) node := f.newNode(KindCallExpression, data) node.Flags |= flags & NodeFlagsOptionalChain return node } func (f *NodeFactory) UpdateCallExpression(node *CallExpression, expression *Expression, questionDotToken *QuestionDotToken, typeArguments *TypeList, arguments *ElementList, flags NodeFlags) *Node { - if expression != node.Expression || questionDotToken != node.QuestionDotToken || typeArguments != node.TypeArguments || arguments != node.Arguments || flags != node.Flags { + if expression != node.Expression() || questionDotToken != node.QuestionDotToken() || typeArguments != node.TypeArguments() || arguments != node.Arguments() || flags != node.Flags { return updateNode(f.NewCallExpression(expression, questionDotToken, typeArguments, arguments, flags), node.AsNode(), f.hooks) } return node.AsNode() } func (node *CallExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) || - visit(v, node.QuestionDotToken) || - visitNodeList(v, node.TypeArguments) || - visitNodeList(v, node.Arguments) + return visit(v, node.Expression()) || + visit(v, node.QuestionDotToken()) || + visitNodeList(v, node.TypeArguments()) || + visitNodeList(v, node.Arguments()) } func (node *CallExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateCallExpression(node, v.visitNode(node.Expression), v.visitNode(node.QuestionDotToken), v.visitNodes(node.TypeArguments), v.visitNodes(node.Arguments), node.Flags) + return v.Factory.UpdateCallExpression(node, v.visitNode(node.Expression()), v.visitNode(node.QuestionDotToken()), v.visitNodes(node.TypeArguments()), v.visitNodes(node.Arguments()), node.Flags) } func (node *CallExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewCallExpression(node.Expression, node.QuestionDotToken, node.TypeArguments, node.Arguments, node.Flags), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewCallExpression(node.Expression(), node.QuestionDotToken(), node.TypeArguments(), node.Arguments(), node.Flags), node.AsNode(), f.AsNodeFactory().hooks) } func IsCallExpression(node *Node) bool { @@ -4308,36 +4859,50 @@ func IsCallExpression(node *Node) bool { type NewExpression struct { PrimaryExpressionBase CompositeBase - Expression *Expression - TypeArguments *TypeList // Optional - Arguments *ElementList // Optional + expression link[Node] // *Expression + typeArguments link[NodeList] // *TypeList. Optional + arguments link[NodeList] // *ElementList. Optional +} + +func (node *NewExpression) Expression() *Expression { return node.expression.get() } + +func (node *NewExpression) SetExpression(expression *Expression) { node.expression.set(expression) } + +func (node *NewExpression) TypeArguments() *TypeList { return node.typeArguments.get() } + +func (node *NewExpression) SetTypeArguments(typeArguments *TypeList) { + node.typeArguments.set(typeArguments) } +func (node *NewExpression) Arguments() *ElementList { return node.arguments.get() } + +func (node *NewExpression) SetArguments(arguments *ElementList) { node.arguments.set(arguments) } + func (f *NodeFactory) NewNewExpression(expression *Expression, typeArguments *TypeList, arguments *ElementList) *Node { - data := &NewExpression{} - data.Expression = expression - data.TypeArguments = typeArguments - data.Arguments = arguments + data := newData[NewExpression](f) + data.expression.set(expression) + data.typeArguments.set(typeArguments) + data.arguments.set(arguments) return f.newNode(KindNewExpression, data) } func (f *NodeFactory) UpdateNewExpression(node *NewExpression, expression *Expression, typeArguments *TypeList, arguments *ElementList) *Node { - if expression != node.Expression || typeArguments != node.TypeArguments || arguments != node.Arguments { + if expression != node.Expression() || typeArguments != node.TypeArguments() || arguments != node.Arguments() { return updateNode(f.NewNewExpression(expression, typeArguments, arguments), node.AsNode(), f.hooks) } return node.AsNode() } func (node *NewExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) || visitNodeList(v, node.TypeArguments) || visitNodeList(v, node.Arguments) + return visit(v, node.Expression()) || visitNodeList(v, node.TypeArguments()) || visitNodeList(v, node.Arguments()) } func (node *NewExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateNewExpression(node, v.visitNode(node.Expression), v.visitNodes(node.TypeArguments), v.visitNodes(node.Arguments)) + return v.Factory.UpdateNewExpression(node, v.visitNode(node.Expression()), v.visitNodes(node.TypeArguments()), v.visitNodes(node.Arguments())) } func (node *NewExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewNewExpression(node.Expression, node.TypeArguments, node.Arguments), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewNewExpression(node.Expression(), node.TypeArguments(), node.Arguments()), node.AsNode(), f.AsNodeFactory().hooks) } func IsNewExpression(node *Node) bool { @@ -4353,37 +4918,37 @@ type MetaProperty struct { FlowNodeBase CompositeBase KeywordToken Kind - name *IdentifierNode + name link[Node] // *IdentifierNode } func (f *NodeFactory) NewMetaProperty(keywordToken Kind, name *IdentifierNode) *Node { - data := &MetaProperty{} + data := newData[MetaProperty](f) data.KeywordToken = keywordToken - data.name = name + data.name.set(name) return f.newNode(KindMetaProperty, data) } func (f *NodeFactory) UpdateMetaProperty(node *MetaProperty, keywordToken Kind, name *IdentifierNode) *Node { - if keywordToken != node.KeywordToken || name != node.name { + if keywordToken != node.KeywordToken || name != node.name.get() { return updateNode(f.NewMetaProperty(keywordToken, name), node.AsNode(), f.hooks) } return node.AsNode() } func (node *MetaProperty) ForEachChild(v Visitor) bool { - return visit(v, node.name) + return visit(v, node.name.get()) } func (node *MetaProperty) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateMetaProperty(node, node.KeywordToken, v.visitNode(node.name)) + return v.Factory.UpdateMetaProperty(node, node.KeywordToken, v.visitNode(node.name.get())) } func (node *MetaProperty) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewMetaProperty(node.KeywordToken, node.name), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewMetaProperty(node.KeywordToken, node.name.get()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *MetaProperty) Name() *DeclarationName { - return node.name + return node.name.get() } func IsMetaProperty(node *Node) bool { @@ -4396,34 +4961,38 @@ func IsMetaProperty(node *Node) bool { type NonNullExpression struct { LeftHandSideExpressionBase - Expression *Expression + expression link[Node] // *Expression } +func (node *NonNullExpression) Expression() *Expression { return node.expression.get() } + +func (node *NonNullExpression) SetExpression(expression *Expression) { node.expression.set(expression) } + func (f *NodeFactory) NewNonNullExpression(expression *Expression, flags NodeFlags) *Node { - data := &NonNullExpression{} - data.Expression = expression + data := newData[NonNullExpression](f) + data.expression.set(expression) node := f.newNode(KindNonNullExpression, data) node.Flags |= flags & NodeFlagsOptionalChain return node } func (f *NodeFactory) UpdateNonNullExpression(node *NonNullExpression, expression *Expression, flags NodeFlags) *Node { - if expression != node.Expression || flags != node.Flags { + if expression != node.Expression() || flags != node.Flags { return updateNode(f.NewNonNullExpression(expression, flags), node.AsNode(), f.hooks) } return node.AsNode() } func (node *NonNullExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) + return visit(v, node.Expression()) } func (node *NonNullExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateNonNullExpression(node, v.visitNode(node.Expression), node.Flags) + return v.Factory.UpdateNonNullExpression(node, v.visitNode(node.Expression()), node.Flags) } func (node *NonNullExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewNonNullExpression(node.Expression, node.Flags), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewNonNullExpression(node.Expression(), node.Flags), node.AsNode(), f.AsNodeFactory().hooks) } func IsNonNullExpression(node *Node) bool { @@ -4436,32 +5005,36 @@ func IsNonNullExpression(node *Node) bool { type SpreadElement struct { ExpressionBase - Expression *Expression + expression link[Node] // *Expression } +func (node *SpreadElement) Expression() *Expression { return node.expression.get() } + +func (node *SpreadElement) SetExpression(expression *Expression) { node.expression.set(expression) } + func (f *NodeFactory) NewSpreadElement(expression *Expression) *Node { - data := &SpreadElement{} - data.Expression = expression + data := newData[SpreadElement](f) + data.expression.set(expression) return f.newNode(KindSpreadElement, data) } func (f *NodeFactory) UpdateSpreadElement(node *SpreadElement, expression *Expression) *Node { - if expression != node.Expression { + if expression != node.Expression() { return updateNode(f.NewSpreadElement(expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *SpreadElement) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) + return visit(v, node.Expression()) } func (node *SpreadElement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateSpreadElement(node, v.visitNode(node.Expression)) + return v.Factory.UpdateSpreadElement(node, v.visitNode(node.Expression())) } func (node *SpreadElement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewSpreadElement(node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewSpreadElement(node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func IsSpreadElement(node *Node) bool { @@ -4475,39 +5048,49 @@ func IsSpreadElement(node *Node) bool { type TemplateExpression struct { PrimaryExpressionBase CompositeBase - Head *TemplateHeadNode - TemplateSpans *TemplateSpanList + head link[Node] // *TemplateHeadNode + templateSpans link[NodeList] // *TemplateSpanList +} + +func (node *TemplateExpression) Head() *TemplateHeadNode { return node.head.get() } + +func (node *TemplateExpression) SetHead(head *TemplateHeadNode) { node.head.set(head) } + +func (node *TemplateExpression) TemplateSpans() *TemplateSpanList { return node.templateSpans.get() } + +func (node *TemplateExpression) SetTemplateSpans(templateSpans *TemplateSpanList) { + node.templateSpans.set(templateSpans) } func (f *NodeFactory) NewTemplateExpression(head *TemplateHeadNode, templateSpans *TemplateSpanList) *Node { - data := &TemplateExpression{} - data.Head = head - data.TemplateSpans = templateSpans + data := newData[TemplateExpression](f) + data.head.set(head) + data.templateSpans.set(templateSpans) return f.newNode(KindTemplateExpression, data) } func (f *NodeFactory) UpdateTemplateExpression(node *TemplateExpression, head *TemplateHeadNode, templateSpans *TemplateSpanList) *Node { - if head != node.Head || templateSpans != node.TemplateSpans { + if head != node.Head() || templateSpans != node.TemplateSpans() { return updateNode(f.NewTemplateExpression(head, templateSpans), node.AsNode(), f.hooks) } return node.AsNode() } func (node *TemplateExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Head) || visitNodeList(v, node.TemplateSpans) + return visit(v, node.Head()) || visitNodeList(v, node.TemplateSpans()) } func (node *TemplateExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateTemplateExpression(node, v.visitNode(node.Head), v.visitNodes(node.TemplateSpans)) + return v.Factory.UpdateTemplateExpression(node, v.visitNode(node.Head()), v.visitNodes(node.TemplateSpans())) } func (node *TemplateExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewTemplateExpression(node.Head, node.TemplateSpans), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewTemplateExpression(node.Head(), node.TemplateSpans()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *TemplateExpression) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Head) | - propagateNodeListSubtreeFacts(node.TemplateSpans, propagateSubtreeFacts) + return propagateSubtreeFacts(node.Head()) | + propagateNodeListSubtreeFacts(node.TemplateSpans(), propagateSubtreeFacts) } func IsTemplateExpression(node *Node) bool { @@ -4520,39 +5103,47 @@ func IsTemplateExpression(node *Node) bool { type TemplateSpan struct { NodeBase - Expression *Expression - Literal *TemplateMiddleOrTail + expression link[Node] // *Expression + literal link[Node] // *TemplateMiddleOrTail } +func (node *TemplateSpan) Expression() *Expression { return node.expression.get() } + +func (node *TemplateSpan) SetExpression(expression *Expression) { node.expression.set(expression) } + +func (node *TemplateSpan) Literal() *TemplateMiddleOrTail { return node.literal.get() } + +func (node *TemplateSpan) SetLiteral(literal *TemplateMiddleOrTail) { node.literal.set(literal) } + func (f *NodeFactory) NewTemplateSpan(expression *Expression, literal *TemplateMiddleOrTail) *Node { - data := &TemplateSpan{} - data.Expression = expression - data.Literal = literal + data := newData[TemplateSpan](f) + data.expression.set(expression) + data.literal.set(literal) return f.newNode(KindTemplateSpan, data) } func (f *NodeFactory) UpdateTemplateSpan(node *TemplateSpan, expression *Expression, literal *TemplateMiddleOrTail) *Node { - if expression != node.Expression || literal != node.Literal { + if expression != node.Expression() || literal != node.Literal() { return updateNode(f.NewTemplateSpan(expression, literal), node.AsNode(), f.hooks) } return node.AsNode() } func (node *TemplateSpan) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) || visit(v, node.Literal) + return visit(v, node.Expression()) || visit(v, node.Literal()) } func (node *TemplateSpan) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateTemplateSpan(node, v.visitNode(node.Expression), v.visitNode(node.Literal)) + return v.Factory.UpdateTemplateSpan(node, v.visitNode(node.Expression()), v.visitNode(node.Literal())) } func (node *TemplateSpan) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewTemplateSpan(node.Expression, node.Literal), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewTemplateSpan(node.Expression(), node.Literal()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *TemplateSpan) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | - propagateSubtreeFacts(node.Literal) + return propagateSubtreeFacts(node.Expression()) | + propagateSubtreeFacts(node.Literal()) } func IsTemplateSpan(node *Node) bool { @@ -4566,43 +5157,67 @@ func IsTemplateSpan(node *Node) bool { type TaggedTemplateExpression struct { MemberExpressionBase CompositeBase - Tag *Expression - QuestionDotToken *QuestionDotToken - TypeArguments *TypeList // Optional - Template *TemplateLiteral + tag link[Node] // *Expression + questionDotToken link[Node] // *QuestionDotToken + typeArguments link[NodeList] // *TypeList. Optional + template link[Node] // *TemplateLiteral +} + +func (node *TaggedTemplateExpression) Tag() *Expression { return node.tag.get() } + +func (node *TaggedTemplateExpression) SetTag(tag *Expression) { node.tag.set(tag) } + +func (node *TaggedTemplateExpression) QuestionDotToken() *QuestionDotToken { + return node.questionDotToken.get() +} + +func (node *TaggedTemplateExpression) SetQuestionDotToken(questionDotToken *QuestionDotToken) { + node.questionDotToken.set(questionDotToken) +} + +func (node *TaggedTemplateExpression) TypeArguments() *TypeList { return node.typeArguments.get() } + +func (node *TaggedTemplateExpression) SetTypeArguments(typeArguments *TypeList) { + node.typeArguments.set(typeArguments) +} + +func (node *TaggedTemplateExpression) Template() *TemplateLiteral { return node.template.get() } + +func (node *TaggedTemplateExpression) SetTemplate(template *TemplateLiteral) { + node.template.set(template) } func (f *NodeFactory) NewTaggedTemplateExpression(tag *Expression, questionDotToken *QuestionDotToken, typeArguments *TypeList, template *TemplateLiteral, flags NodeFlags) *Node { - data := &TaggedTemplateExpression{} - data.Tag = tag - data.QuestionDotToken = questionDotToken - data.TypeArguments = typeArguments - data.Template = template + data := newData[TaggedTemplateExpression](f) + data.tag.set(tag) + data.questionDotToken.set(questionDotToken) + data.typeArguments.set(typeArguments) + data.template.set(template) node := f.newNode(KindTaggedTemplateExpression, data) node.Flags |= flags & NodeFlagsOptionalChain return node } func (f *NodeFactory) UpdateTaggedTemplateExpression(node *TaggedTemplateExpression, tag *Expression, questionDotToken *QuestionDotToken, typeArguments *TypeList, template *TemplateLiteral, flags NodeFlags) *Node { - if tag != node.Tag || questionDotToken != node.QuestionDotToken || typeArguments != node.TypeArguments || template != node.Template || flags != node.Flags { + if tag != node.Tag() || questionDotToken != node.QuestionDotToken() || typeArguments != node.TypeArguments() || template != node.Template() || flags != node.Flags { return updateNode(f.NewTaggedTemplateExpression(tag, questionDotToken, typeArguments, template, flags), node.AsNode(), f.hooks) } return node.AsNode() } func (node *TaggedTemplateExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Tag) || - visit(v, node.QuestionDotToken) || - visitNodeList(v, node.TypeArguments) || - visit(v, node.Template) + return visit(v, node.Tag()) || + visit(v, node.QuestionDotToken()) || + visitNodeList(v, node.TypeArguments()) || + visit(v, node.Template()) } func (node *TaggedTemplateExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateTaggedTemplateExpression(node, v.visitNode(node.Tag), v.visitNode(node.QuestionDotToken), v.visitNodes(node.TypeArguments), v.visitNode(node.Template), node.Flags) + return v.Factory.UpdateTaggedTemplateExpression(node, v.visitNode(node.Tag()), v.visitNode(node.QuestionDotToken()), v.visitNodes(node.TypeArguments()), v.visitNode(node.Template()), node.Flags) } func (node *TaggedTemplateExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewTaggedTemplateExpression(node.Tag, node.QuestionDotToken, node.TypeArguments, node.Template, node.Flags), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewTaggedTemplateExpression(node.Tag(), node.QuestionDotToken(), node.TypeArguments(), node.Template(), node.Flags), node.AsNode(), f.AsNodeFactory().hooks) } func IsTaggedTemplateExpression(node *Node) bool { @@ -4615,36 +5230,42 @@ func IsTaggedTemplateExpression(node *Node) bool { type ParenthesizedExpression struct { PrimaryExpressionBase - Expression *Expression + expression link[Node] // *Expression +} + +func (node *ParenthesizedExpression) Expression() *Expression { return node.expression.get() } + +func (node *ParenthesizedExpression) SetExpression(expression *Expression) { + node.expression.set(expression) } func (f *NodeFactory) NewParenthesizedExpression(expression *Expression) *Node { - data := f.parenthesizedExpressionArena.New() - data.Expression = expression + data := newData[ParenthesizedExpression](f) + data.expression.set(expression) return f.newNode(KindParenthesizedExpression, data) } func (f *NodeFactory) UpdateParenthesizedExpression(node *ParenthesizedExpression, expression *Expression) *Node { - if expression != node.Expression { + if expression != node.Expression() { return updateNode(f.NewParenthesizedExpression(expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ParenthesizedExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) + return visit(v, node.Expression()) } func (node *ParenthesizedExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateParenthesizedExpression(node, v.visitNode(node.Expression)) + return v.Factory.UpdateParenthesizedExpression(node, v.visitNode(node.Expression())) } func (node *ParenthesizedExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewParenthesizedExpression(node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewParenthesizedExpression(node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ParenthesizedExpression) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) + return propagateSubtreeFacts(node.Expression()) } func IsParenthesizedExpression(node *Node) bool { @@ -4658,38 +5279,42 @@ func IsParenthesizedExpression(node *Node) bool { type ArrayLiteralExpression struct { PrimaryExpressionBase CompositeBase - Elements *ElementList + elements link[NodeList] // *ElementList MultiLine bool } +func (node *ArrayLiteralExpression) Elements() *ElementList { return node.elements.get() } + +func (node *ArrayLiteralExpression) SetElements(elements *ElementList) { node.elements.set(elements) } + func (f *NodeFactory) NewArrayLiteralExpression(elements *ElementList, multiLine bool) *Node { - data := &ArrayLiteralExpression{} - data.Elements = elements + data := newData[ArrayLiteralExpression](f) + data.elements.set(elements) data.MultiLine = multiLine return f.newNode(KindArrayLiteralExpression, data) } func (f *NodeFactory) UpdateArrayLiteralExpression(node *ArrayLiteralExpression, elements *ElementList, multiLine bool) *Node { - if elements != node.Elements || multiLine != node.MultiLine { + if elements != node.Elements() || multiLine != node.MultiLine { return updateNode(f.NewArrayLiteralExpression(elements, multiLine), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ArrayLiteralExpression) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.Elements) + return visitNodeList(v, node.Elements()) } func (node *ArrayLiteralExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateArrayLiteralExpression(node, v.visitNodes(node.Elements), node.MultiLine) + return v.Factory.UpdateArrayLiteralExpression(node, v.visitNodes(node.Elements()), node.MultiLine) } func (node *ArrayLiteralExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewArrayLiteralExpression(node.Elements, node.MultiLine), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewArrayLiteralExpression(node.Elements(), node.MultiLine), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ArrayLiteralExpression) computeSubtreeFacts() SubtreeFacts { - return propagateNodeListSubtreeFacts(node.Elements, propagateSubtreeFacts) + return propagateNodeListSubtreeFacts(node.Elements(), propagateSubtreeFacts) } func IsArrayLiteralExpression(node *Node) bool { @@ -4704,38 +5329,44 @@ type ObjectLiteralExpression struct { PrimaryExpressionBase DeclarationBase CompositeBase - Properties *NodeList + properties link[NodeList] // *NodeList MultiLine bool } +func (node *ObjectLiteralExpression) Properties() *NodeList { return node.properties.get() } + +func (node *ObjectLiteralExpression) SetProperties(properties *NodeList) { + node.properties.set(properties) +} + func (f *NodeFactory) NewObjectLiteralExpression(properties *NodeList, multiLine bool) *Node { - data := &ObjectLiteralExpression{} - data.Properties = properties + data := newData[ObjectLiteralExpression](f) + data.properties.set(properties) data.MultiLine = multiLine return f.newNode(KindObjectLiteralExpression, data) } func (f *NodeFactory) UpdateObjectLiteralExpression(node *ObjectLiteralExpression, properties *NodeList, multiLine bool) *Node { - if properties != node.Properties || multiLine != node.MultiLine { + if properties != node.Properties() || multiLine != node.MultiLine { return updateNode(f.NewObjectLiteralExpression(properties, multiLine), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ObjectLiteralExpression) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.Properties) + return visitNodeList(v, node.Properties()) } func (node *ObjectLiteralExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateObjectLiteralExpression(node, v.visitNodes(node.Properties), node.MultiLine) + return v.Factory.UpdateObjectLiteralExpression(node, v.visitNodes(node.Properties()), node.MultiLine) } func (node *ObjectLiteralExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewObjectLiteralExpression(node.Properties, node.MultiLine), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewObjectLiteralExpression(node.Properties(), node.MultiLine), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ObjectLiteralExpression) computeSubtreeFacts() SubtreeFacts { - return propagateNodeListSubtreeFacts(node.Properties, propagateSubtreeFacts) + return propagateNodeListSubtreeFacts(node.Properties(), propagateSubtreeFacts) } func IsObjectLiteralExpression(node *Node) bool { @@ -4750,32 +5381,36 @@ type SpreadAssignment struct { ObjectLiteralElementBase NodeBase DeclarationBase - Expression *Expression + expression link[Node] // *Expression } +func (node *SpreadAssignment) Expression() *Expression { return node.expression.get() } + +func (node *SpreadAssignment) SetExpression(expression *Expression) { node.expression.set(expression) } + func (f *NodeFactory) NewSpreadAssignment(expression *Expression) *Node { - data := &SpreadAssignment{} - data.Expression = expression + data := newData[SpreadAssignment](f) + data.expression.set(expression) return f.newNode(KindSpreadAssignment, data) } func (f *NodeFactory) UpdateSpreadAssignment(node *SpreadAssignment, expression *Expression) *Node { - if expression != node.Expression { + if expression != node.Expression() { return updateNode(f.NewSpreadAssignment(expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *SpreadAssignment) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) + return visit(v, node.Expression()) } func (node *SpreadAssignment) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateSpreadAssignment(node, v.visitNode(node.Expression)) + return v.Factory.UpdateSpreadAssignment(node, v.visitNode(node.Expression())) } func (node *SpreadAssignment) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewSpreadAssignment(node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewSpreadAssignment(node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func IsSpreadAssignment(node *Node) bool { @@ -4792,45 +5427,55 @@ type PropertyAssignment struct { DeclarationBase NamedMemberBase CompositeBase - Type *TypeNode - Initializer *Expression + typeNode link[Node] // *TypeNode + initializer link[Node] // *Expression +} + +func (node *PropertyAssignment) Type() *TypeNode { return node.typeNode.get() } + +func (node *PropertyAssignment) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + +func (node *PropertyAssignment) Initializer() *Expression { return node.initializer.get() } + +func (node *PropertyAssignment) SetInitializer(initializer *Expression) { + node.initializer.set(initializer) } func (f *NodeFactory) NewPropertyAssignment(modifiers *ModifierList, name *PropertyName, postfixToken *TokenNode, typeNode *TypeNode, initializer *Expression) *Node { - data := f.propertyAssignmentArena.New() - data.modifiers = modifiers - data.name = name - data.PostfixToken = postfixToken - data.Type = typeNode - data.Initializer = initializer + data := newData[PropertyAssignment](f) + data.modifiers.set(modifiers) + data.name.set(name) + data.postfixToken.set(postfixToken) + data.typeNode.set(typeNode) + data.initializer.set(initializer) return f.newNode(KindPropertyAssignment, data) } func (f *NodeFactory) UpdatePropertyAssignment(node *PropertyAssignment, modifiers *ModifierList, name *PropertyName, postfixToken *TokenNode, typeNode *TypeNode, initializer *Expression) *Node { - if modifiers != node.modifiers || name != node.name || postfixToken != node.PostfixToken || typeNode != node.Type || initializer != node.Initializer { + if modifiers != node.modifiers.get() || name != node.name.get() || postfixToken != node.PostfixToken() || typeNode != node.Type() || initializer != node.Initializer() { return updateNode(f.NewPropertyAssignment(modifiers, name, postfixToken, typeNode, initializer), node.AsNode(), f.hooks) } return node.AsNode() } func (node *PropertyAssignment) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.name) || - visit(v, node.PostfixToken) || - visit(v, node.Type) || - visit(v, node.Initializer) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.name.get()) || + visit(v, node.PostfixToken()) || + visit(v, node.Type()) || + visit(v, node.Initializer()) } func (node *PropertyAssignment) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdatePropertyAssignment(node, v.visitModifiers(node.modifiers), v.visitNode(node.name), v.visitNode(node.PostfixToken), v.visitNode(node.Type), v.visitNode(node.Initializer)) + return v.Factory.UpdatePropertyAssignment(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.name.get()), v.visitNode(node.PostfixToken()), v.visitNode(node.Type()), v.visitNode(node.Initializer())) } func (node *PropertyAssignment) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewPropertyAssignment(node.Modifiers(), node.name, node.PostfixToken, node.Type, node.Initializer), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewPropertyAssignment(node.Modifiers(), node.name.get(), node.PostfixToken(), node.Type(), node.Initializer()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *PropertyAssignment) Name() *DeclarationName { - return node.name + return node.name.get() } func IsPropertyAssignment(node *Node) bool { @@ -4847,48 +5492,66 @@ type ShorthandPropertyAssignment struct { DeclarationBase NamedMemberBase CompositeBase - Type *TypeNode - EqualsToken *EqualsToken // Optional - ObjectAssignmentInitializer *Expression // Optional + typeNode link[Node] // *TypeNode + equalsToken link[Node] // *EqualsToken. Optional + objectAssignmentInitializer link[Node] // *Expression. Optional +} + +func (node *ShorthandPropertyAssignment) Type() *TypeNode { return node.typeNode.get() } + +func (node *ShorthandPropertyAssignment) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + +func (node *ShorthandPropertyAssignment) EqualsToken() *EqualsToken { return node.equalsToken.get() } + +func (node *ShorthandPropertyAssignment) SetEqualsToken(equalsToken *EqualsToken) { + node.equalsToken.set(equalsToken) +} + +func (node *ShorthandPropertyAssignment) ObjectAssignmentInitializer() *Expression { + return node.objectAssignmentInitializer.get() +} + +func (node *ShorthandPropertyAssignment) SetObjectAssignmentInitializer(objectAssignmentInitializer *Expression) { + node.objectAssignmentInitializer.set(objectAssignmentInitializer) } func (f *NodeFactory) NewShorthandPropertyAssignment(modifiers *ModifierList, name *PropertyName, postfixToken *TokenNode, typeNode *TypeNode, equalsToken *EqualsToken, objectAssignmentInitializer *Expression) *Node { - data := &ShorthandPropertyAssignment{} - data.modifiers = modifiers - data.name = name - data.PostfixToken = postfixToken - data.Type = typeNode - data.EqualsToken = equalsToken - data.ObjectAssignmentInitializer = objectAssignmentInitializer + data := newData[ShorthandPropertyAssignment](f) + data.modifiers.set(modifiers) + data.name.set(name) + data.postfixToken.set(postfixToken) + data.typeNode.set(typeNode) + data.equalsToken.set(equalsToken) + data.objectAssignmentInitializer.set(objectAssignmentInitializer) return f.newNode(KindShorthandPropertyAssignment, data) } func (f *NodeFactory) UpdateShorthandPropertyAssignment(node *ShorthandPropertyAssignment, modifiers *ModifierList, name *PropertyName, postfixToken *TokenNode, typeNode *TypeNode, equalsToken *EqualsToken, objectAssignmentInitializer *Expression) *Node { - if modifiers != node.modifiers || name != node.name || postfixToken != node.PostfixToken || typeNode != node.Type || equalsToken != node.EqualsToken || objectAssignmentInitializer != node.ObjectAssignmentInitializer { + if modifiers != node.modifiers.get() || name != node.name.get() || postfixToken != node.PostfixToken() || typeNode != node.Type() || equalsToken != node.EqualsToken() || objectAssignmentInitializer != node.ObjectAssignmentInitializer() { return updateNode(f.NewShorthandPropertyAssignment(modifiers, name, postfixToken, typeNode, equalsToken, objectAssignmentInitializer), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ShorthandPropertyAssignment) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.name) || - visit(v, node.PostfixToken) || - visit(v, node.Type) || - visit(v, node.EqualsToken) || - visit(v, node.ObjectAssignmentInitializer) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.name.get()) || + visit(v, node.PostfixToken()) || + visit(v, node.Type()) || + visit(v, node.EqualsToken()) || + visit(v, node.ObjectAssignmentInitializer()) } func (node *ShorthandPropertyAssignment) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateShorthandPropertyAssignment(node, v.visitModifiers(node.modifiers), v.visitNode(node.name), v.visitNode(node.PostfixToken), v.visitNode(node.Type), v.visitNode(node.EqualsToken), v.visitNode(node.ObjectAssignmentInitializer)) + return v.Factory.UpdateShorthandPropertyAssignment(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.name.get()), v.visitNode(node.PostfixToken()), v.visitNode(node.Type()), v.visitNode(node.EqualsToken()), v.visitNode(node.ObjectAssignmentInitializer())) } func (node *ShorthandPropertyAssignment) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewShorthandPropertyAssignment(node.Modifiers(), node.name, node.PostfixToken, node.Type, node.EqualsToken, node.ObjectAssignmentInitializer), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewShorthandPropertyAssignment(node.Modifiers(), node.name.get(), node.PostfixToken(), node.Type(), node.EqualsToken(), node.ObjectAssignmentInitializer()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ShorthandPropertyAssignment) Name() *DeclarationName { - return node.name + return node.name.get() } func IsShorthandPropertyAssignment(node *Node) bool { @@ -4901,36 +5564,40 @@ func IsShorthandPropertyAssignment(node *Node) bool { type DeleteExpression struct { UnaryExpressionBase - Expression *Expression + expression link[Node] // *Expression } +func (node *DeleteExpression) Expression() *Expression { return node.expression.get() } + +func (node *DeleteExpression) SetExpression(expression *Expression) { node.expression.set(expression) } + func (f *NodeFactory) NewDeleteExpression(expression *Expression) *Node { - data := &DeleteExpression{} - data.Expression = expression + data := newData[DeleteExpression](f) + data.expression.set(expression) return f.newNode(KindDeleteExpression, data) } func (f *NodeFactory) UpdateDeleteExpression(node *DeleteExpression, expression *Expression) *Node { - if expression != node.Expression { + if expression != node.Expression() { return updateNode(f.NewDeleteExpression(expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *DeleteExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) + return visit(v, node.Expression()) } func (node *DeleteExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateDeleteExpression(node, v.visitNode(node.Expression)) + return v.Factory.UpdateDeleteExpression(node, v.visitNode(node.Expression())) } func (node *DeleteExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewDeleteExpression(node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewDeleteExpression(node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *DeleteExpression) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) + return propagateSubtreeFacts(node.Expression()) } func IsDeleteExpression(node *Node) bool { @@ -4943,36 +5610,40 @@ func IsDeleteExpression(node *Node) bool { type TypeOfExpression struct { UnaryExpressionBase - Expression *Expression + expression link[Node] // *Expression } +func (node *TypeOfExpression) Expression() *Expression { return node.expression.get() } + +func (node *TypeOfExpression) SetExpression(expression *Expression) { node.expression.set(expression) } + func (f *NodeFactory) NewTypeOfExpression(expression *Expression) *Node { - data := &TypeOfExpression{} - data.Expression = expression + data := newData[TypeOfExpression](f) + data.expression.set(expression) return f.newNode(KindTypeOfExpression, data) } func (f *NodeFactory) UpdateTypeOfExpression(node *TypeOfExpression, expression *Expression) *Node { - if expression != node.Expression { + if expression != node.Expression() { return updateNode(f.NewTypeOfExpression(expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *TypeOfExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) + return visit(v, node.Expression()) } func (node *TypeOfExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateTypeOfExpression(node, v.visitNode(node.Expression)) + return v.Factory.UpdateTypeOfExpression(node, v.visitNode(node.Expression())) } func (node *TypeOfExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewTypeOfExpression(node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewTypeOfExpression(node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *TypeOfExpression) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) + return propagateSubtreeFacts(node.Expression()) } func IsTypeOfExpression(node *Node) bool { @@ -4985,36 +5656,40 @@ func IsTypeOfExpression(node *Node) bool { type VoidExpression struct { UnaryExpressionBase - Expression *Expression + expression link[Node] // *Expression } +func (node *VoidExpression) Expression() *Expression { return node.expression.get() } + +func (node *VoidExpression) SetExpression(expression *Expression) { node.expression.set(expression) } + func (f *NodeFactory) NewVoidExpression(expression *Expression) *Node { - data := &VoidExpression{} - data.Expression = expression + data := newData[VoidExpression](f) + data.expression.set(expression) return f.newNode(KindVoidExpression, data) } func (f *NodeFactory) UpdateVoidExpression(node *VoidExpression, expression *Expression) *Node { - if expression != node.Expression { + if expression != node.Expression() { return updateNode(f.NewVoidExpression(expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *VoidExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) + return visit(v, node.Expression()) } func (node *VoidExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateVoidExpression(node, v.visitNode(node.Expression)) + return v.Factory.UpdateVoidExpression(node, v.visitNode(node.Expression())) } func (node *VoidExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewVoidExpression(node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewVoidExpression(node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *VoidExpression) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) + return propagateSubtreeFacts(node.Expression()) } func IsVoidExpression(node *Node) bool { @@ -5027,32 +5702,36 @@ func IsVoidExpression(node *Node) bool { type AwaitExpression struct { UnaryExpressionBase - Expression *Expression + expression link[Node] // *Expression } +func (node *AwaitExpression) Expression() *Expression { return node.expression.get() } + +func (node *AwaitExpression) SetExpression(expression *Expression) { node.expression.set(expression) } + func (f *NodeFactory) NewAwaitExpression(expression *Expression) *Node { - data := &AwaitExpression{} - data.Expression = expression + data := newData[AwaitExpression](f) + data.expression.set(expression) return f.newNode(KindAwaitExpression, data) } func (f *NodeFactory) UpdateAwaitExpression(node *AwaitExpression, expression *Expression) *Node { - if expression != node.Expression { + if expression != node.Expression() { return updateNode(f.NewAwaitExpression(expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *AwaitExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) + return visit(v, node.Expression()) } func (node *AwaitExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateAwaitExpression(node, v.visitNode(node.Expression)) + return v.Factory.UpdateAwaitExpression(node, v.visitNode(node.Expression())) } func (node *AwaitExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewAwaitExpression(node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewAwaitExpression(node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func IsAwaitExpression(node *Node) bool { @@ -5065,34 +5744,42 @@ func IsAwaitExpression(node *Node) bool { type TypeAssertion struct { UnaryExpressionBase - Type *TypeNode - Expression *Expression + typeNode link[Node] // *TypeNode + expression link[Node] // *Expression } +func (node *TypeAssertion) Type() *TypeNode { return node.typeNode.get() } + +func (node *TypeAssertion) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + +func (node *TypeAssertion) Expression() *Expression { return node.expression.get() } + +func (node *TypeAssertion) SetExpression(expression *Expression) { node.expression.set(expression) } + func (f *NodeFactory) NewTypeAssertion(typeNode *TypeNode, expression *Expression) *Node { - data := &TypeAssertion{} - data.Type = typeNode - data.Expression = expression + data := newData[TypeAssertion](f) + data.typeNode.set(typeNode) + data.expression.set(expression) return f.newNode(KindTypeAssertionExpression, data) } func (f *NodeFactory) UpdateTypeAssertion(node *TypeAssertion, typeNode *TypeNode, expression *Expression) *Node { - if typeNode != node.Type || expression != node.Expression { + if typeNode != node.Type() || expression != node.Expression() { return updateNode(f.NewTypeAssertion(typeNode, expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *TypeAssertion) ForEachChild(v Visitor) bool { - return visit(v, node.Type) || visit(v, node.Expression) + return visit(v, node.Type()) || visit(v, node.Expression()) } func (node *TypeAssertion) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateTypeAssertion(node, v.visitNode(node.Type), v.visitNode(node.Expression)) + return v.Factory.UpdateTypeAssertion(node, v.visitNode(node.Type()), v.visitNode(node.Expression())) } func (node *TypeAssertion) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewTypeAssertion(node.Type, node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewTypeAssertion(node.Type(), node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func IsTypeAssertion(node *Node) bool { @@ -5108,7 +5795,7 @@ type KeywordTypeNode struct { } func (f *NodeFactory) NewKeywordTypeNode(kind KeywordTypeSyntaxKind) *Node { - data := f.keywordTypeNodeArena.New() + data := newData[KeywordTypeNode](f) return f.newNode(kind, data) } @@ -5133,28 +5820,28 @@ type UnionTypeNode struct { } func (f *NodeFactory) NewUnionTypeNode(types *TypeList) *Node { - data := f.unionTypeNodeArena.New() - data.Types = types + data := newData[UnionTypeNode](f) + data.types.set(types) return f.newNode(KindUnionType, data) } func (f *NodeFactory) UpdateUnionTypeNode(node *UnionTypeNode, types *TypeList) *Node { - if types != node.Types { + if types != node.Types() { return updateNode(f.NewUnionTypeNode(types), node.AsNode(), f.hooks) } return node.AsNode() } func (node *UnionTypeNode) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.Types) + return visitNodeList(v, node.Types()) } func (node *UnionTypeNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateUnionTypeNode(node, v.visitNodes(node.Types)) + return v.Factory.UpdateUnionTypeNode(node, v.visitNodes(node.Types())) } func (node *UnionTypeNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewUnionTypeNode(node.Types), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewUnionTypeNode(node.Types()), node.AsNode(), f.AsNodeFactory().hooks) } func IsUnionTypeNode(node *Node) bool { @@ -5170,28 +5857,28 @@ type IntersectionTypeNode struct { } func (f *NodeFactory) NewIntersectionTypeNode(types *TypeList) *Node { - data := f.intersectionTypeNodeArena.New() - data.Types = types + data := newData[IntersectionTypeNode](f) + data.types.set(types) return f.newNode(KindIntersectionType, data) } func (f *NodeFactory) UpdateIntersectionTypeNode(node *IntersectionTypeNode, types *TypeList) *Node { - if types != node.Types { + if types != node.Types() { return updateNode(f.NewIntersectionTypeNode(types), node.AsNode(), f.hooks) } return node.AsNode() } func (node *IntersectionTypeNode) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.Types) + return visitNodeList(v, node.Types()) } func (node *IntersectionTypeNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateIntersectionTypeNode(node, v.visitNodes(node.Types)) + return v.Factory.UpdateIntersectionTypeNode(node, v.visitNodes(node.Types())) } func (node *IntersectionTypeNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewIntersectionTypeNode(node.Types), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewIntersectionTypeNode(node.Types()), node.AsNode(), f.AsNodeFactory().hooks) } func IsIntersectionTypeNode(node *Node) bool { @@ -5205,41 +5892,59 @@ func IsIntersectionTypeNode(node *Node) bool { type ConditionalTypeNode struct { TypeNodeBase LocalsContainerBase - CheckType *TypeNode - ExtendsType *TypeNode - TrueType *TypeNode - FalseType *TypeNode + checkType link[Node] // *TypeNode + extendsType link[Node] // *TypeNode + trueType link[Node] // *TypeNode + falseType link[Node] // *TypeNode } +func (node *ConditionalTypeNode) CheckType() *TypeNode { return node.checkType.get() } + +func (node *ConditionalTypeNode) SetCheckType(checkType *TypeNode) { node.checkType.set(checkType) } + +func (node *ConditionalTypeNode) ExtendsType() *TypeNode { return node.extendsType.get() } + +func (node *ConditionalTypeNode) SetExtendsType(extendsType *TypeNode) { + node.extendsType.set(extendsType) +} + +func (node *ConditionalTypeNode) TrueType() *TypeNode { return node.trueType.get() } + +func (node *ConditionalTypeNode) SetTrueType(trueType *TypeNode) { node.trueType.set(trueType) } + +func (node *ConditionalTypeNode) FalseType() *TypeNode { return node.falseType.get() } + +func (node *ConditionalTypeNode) SetFalseType(falseType *TypeNode) { node.falseType.set(falseType) } + func (f *NodeFactory) NewConditionalTypeNode(checkType *TypeNode, extendsType *TypeNode, trueType *TypeNode, falseType *TypeNode) *Node { - data := &ConditionalTypeNode{} - data.CheckType = checkType - data.ExtendsType = extendsType - data.TrueType = trueType - data.FalseType = falseType + data := newData[ConditionalTypeNode](f) + data.checkType.set(checkType) + data.extendsType.set(extendsType) + data.trueType.set(trueType) + data.falseType.set(falseType) return f.newNode(KindConditionalType, data) } func (f *NodeFactory) UpdateConditionalTypeNode(node *ConditionalTypeNode, checkType *TypeNode, extendsType *TypeNode, trueType *TypeNode, falseType *TypeNode) *Node { - if checkType != node.CheckType || extendsType != node.ExtendsType || trueType != node.TrueType || falseType != node.FalseType { + if checkType != node.CheckType() || extendsType != node.ExtendsType() || trueType != node.TrueType() || falseType != node.FalseType() { return updateNode(f.NewConditionalTypeNode(checkType, extendsType, trueType, falseType), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ConditionalTypeNode) ForEachChild(v Visitor) bool { - return visit(v, node.CheckType) || - visit(v, node.ExtendsType) || - visit(v, node.TrueType) || - visit(v, node.FalseType) + return visit(v, node.CheckType()) || + visit(v, node.ExtendsType()) || + visit(v, node.TrueType()) || + visit(v, node.FalseType()) } func (node *ConditionalTypeNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateConditionalTypeNode(node, v.visitNode(node.CheckType), v.visitNode(node.ExtendsType), v.visitNode(node.TrueType), v.visitNode(node.FalseType)) + return v.Factory.UpdateConditionalTypeNode(node, v.visitNode(node.CheckType()), v.visitNode(node.ExtendsType()), v.visitNode(node.TrueType()), v.visitNode(node.FalseType())) } func (node *ConditionalTypeNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewConditionalTypeNode(node.CheckType, node.ExtendsType, node.TrueType, node.FalseType), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewConditionalTypeNode(node.CheckType(), node.ExtendsType(), node.TrueType(), node.FalseType()), node.AsNode(), f.AsNodeFactory().hooks) } func IsConditionalTypeNode(node *Node) bool { @@ -5253,33 +5958,37 @@ func IsConditionalTypeNode(node *Node) bool { type TypeOperatorNode struct { TypeNodeBase Operator Kind - Type *TypeNode + typeNode link[Node] // *TypeNode } +func (node *TypeOperatorNode) Type() *TypeNode { return node.typeNode.get() } + +func (node *TypeOperatorNode) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + func (f *NodeFactory) NewTypeOperatorNode(operator Kind, typeNode *TypeNode) *Node { - data := f.typeOperatorNodeArena.New() + data := newData[TypeOperatorNode](f) data.Operator = operator - data.Type = typeNode + data.typeNode.set(typeNode) return f.newNode(KindTypeOperator, data) } func (f *NodeFactory) UpdateTypeOperatorNode(node *TypeOperatorNode, operator Kind, typeNode *TypeNode) *Node { - if operator != node.Operator || typeNode != node.Type { + if operator != node.Operator || typeNode != node.Type() { return updateNode(f.NewTypeOperatorNode(operator, typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *TypeOperatorNode) ForEachChild(v Visitor) bool { - return visit(v, node.Type) + return visit(v, node.Type()) } func (node *TypeOperatorNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateTypeOperatorNode(node, node.Operator, v.visitNode(node.Type)) + return v.Factory.UpdateTypeOperatorNode(node, node.Operator, v.visitNode(node.Type())) } func (node *TypeOperatorNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewTypeOperatorNode(node.Operator, node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewTypeOperatorNode(node.Operator, node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func IsTypeOperatorNode(node *Node) bool { @@ -5292,32 +6001,40 @@ func IsTypeOperatorNode(node *Node) bool { type InferTypeNode struct { TypeNodeBase - TypeParameter *TypeParameterDeclarationNode + typeParameter link[Node] // *TypeParameterDeclarationNode +} + +func (node *InferTypeNode) TypeParameter() *TypeParameterDeclarationNode { + return node.typeParameter.get() +} + +func (node *InferTypeNode) SetTypeParameter(typeParameter *TypeParameterDeclarationNode) { + node.typeParameter.set(typeParameter) } func (f *NodeFactory) NewInferTypeNode(typeParameter *TypeParameterDeclarationNode) *Node { - data := &InferTypeNode{} - data.TypeParameter = typeParameter + data := newData[InferTypeNode](f) + data.typeParameter.set(typeParameter) return f.newNode(KindInferType, data) } func (f *NodeFactory) UpdateInferTypeNode(node *InferTypeNode, typeParameter *TypeParameterDeclarationNode) *Node { - if typeParameter != node.TypeParameter { + if typeParameter != node.TypeParameter() { return updateNode(f.NewInferTypeNode(typeParameter), node.AsNode(), f.hooks) } return node.AsNode() } func (node *InferTypeNode) ForEachChild(v Visitor) bool { - return visit(v, node.TypeParameter) + return visit(v, node.TypeParameter()) } func (node *InferTypeNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateInferTypeNode(node, v.visitNode(node.TypeParameter)) + return v.Factory.UpdateInferTypeNode(node, v.visitNode(node.TypeParameter())) } func (node *InferTypeNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewInferTypeNode(node.TypeParameter), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewInferTypeNode(node.TypeParameter()), node.AsNode(), f.AsNodeFactory().hooks) } func IsInferTypeNode(node *Node) bool { @@ -5330,32 +6047,36 @@ func IsInferTypeNode(node *Node) bool { type ArrayTypeNode struct { TypeNodeBase - ElementType *TypeNode + elementType link[Node] // *TypeNode } +func (node *ArrayTypeNode) ElementType() *TypeNode { return node.elementType.get() } + +func (node *ArrayTypeNode) SetElementType(elementType *TypeNode) { node.elementType.set(elementType) } + func (f *NodeFactory) NewArrayTypeNode(elementType *TypeNode) *Node { - data := f.arrayTypeNodeArena.New() - data.ElementType = elementType + data := newData[ArrayTypeNode](f) + data.elementType.set(elementType) return f.newNode(KindArrayType, data) } func (f *NodeFactory) UpdateArrayTypeNode(node *ArrayTypeNode, elementType *TypeNode) *Node { - if elementType != node.ElementType { + if elementType != node.ElementType() { return updateNode(f.NewArrayTypeNode(elementType), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ArrayTypeNode) ForEachChild(v Visitor) bool { - return visit(v, node.ElementType) + return visit(v, node.ElementType()) } func (node *ArrayTypeNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateArrayTypeNode(node, v.visitNode(node.ElementType)) + return v.Factory.UpdateArrayTypeNode(node, v.visitNode(node.ElementType())) } func (node *ArrayTypeNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewArrayTypeNode(node.ElementType), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewArrayTypeNode(node.ElementType()), node.AsNode(), f.AsNodeFactory().hooks) } func IsArrayTypeNode(node *Node) bool { @@ -5368,34 +6089,44 @@ func IsArrayTypeNode(node *Node) bool { type IndexedAccessTypeNode struct { TypeNodeBase - ObjectType *TypeNode - IndexType *TypeNode + objectType link[Node] // *TypeNode + indexType link[Node] // *TypeNode +} + +func (node *IndexedAccessTypeNode) ObjectType() *TypeNode { return node.objectType.get() } + +func (node *IndexedAccessTypeNode) SetObjectType(objectType *TypeNode) { + node.objectType.set(objectType) } +func (node *IndexedAccessTypeNode) IndexType() *TypeNode { return node.indexType.get() } + +func (node *IndexedAccessTypeNode) SetIndexType(indexType *TypeNode) { node.indexType.set(indexType) } + func (f *NodeFactory) NewIndexedAccessTypeNode(objectType *TypeNode, indexType *TypeNode) *Node { - data := f.indexedAccessTypeNodeArena.New() - data.ObjectType = objectType - data.IndexType = indexType + data := newData[IndexedAccessTypeNode](f) + data.objectType.set(objectType) + data.indexType.set(indexType) return f.newNode(KindIndexedAccessType, data) } func (f *NodeFactory) UpdateIndexedAccessTypeNode(node *IndexedAccessTypeNode, objectType *TypeNode, indexType *TypeNode) *Node { - if objectType != node.ObjectType || indexType != node.IndexType { + if objectType != node.ObjectType() || indexType != node.IndexType() { return updateNode(f.NewIndexedAccessTypeNode(objectType, indexType), node.AsNode(), f.hooks) } return node.AsNode() } func (node *IndexedAccessTypeNode) ForEachChild(v Visitor) bool { - return visit(v, node.ObjectType) || visit(v, node.IndexType) + return visit(v, node.ObjectType()) || visit(v, node.IndexType()) } func (node *IndexedAccessTypeNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateIndexedAccessTypeNode(node, v.visitNode(node.ObjectType), v.visitNode(node.IndexType)) + return v.Factory.UpdateIndexedAccessTypeNode(node, v.visitNode(node.ObjectType()), v.visitNode(node.IndexType())) } func (node *IndexedAccessTypeNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewIndexedAccessTypeNode(node.ObjectType, node.IndexType), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewIndexedAccessTypeNode(node.ObjectType(), node.IndexType()), node.AsNode(), f.AsNodeFactory().hooks) } func IsIndexedAccessTypeNode(node *Node) bool { @@ -5408,33 +6139,37 @@ func IsIndexedAccessTypeNode(node *Node) bool { type TypeReferenceNode struct { NodeWithTypeArgumentsBase - TypeName *EntityName + typeName link[Node] // *EntityName } +func (node *TypeReferenceNode) TypeName() *EntityName { return node.typeName.get() } + +func (node *TypeReferenceNode) SetTypeName(typeName *EntityName) { node.typeName.set(typeName) } + func (f *NodeFactory) NewTypeReferenceNode(typeName *EntityName, typeArguments *TypeList) *Node { - data := f.typeReferenceNodeArena.New() - data.TypeName = typeName - data.TypeArguments = typeArguments + data := newData[TypeReferenceNode](f) + data.typeName.set(typeName) + data.typeArguments.set(typeArguments) return f.newNode(KindTypeReference, data) } func (f *NodeFactory) UpdateTypeReferenceNode(node *TypeReferenceNode, typeName *EntityName, typeArguments *TypeList) *Node { - if typeName != node.TypeName || typeArguments != node.TypeArguments { + if typeName != node.TypeName() || typeArguments != node.TypeArguments() { return updateNode(f.NewTypeReferenceNode(typeName, typeArguments), node.AsNode(), f.hooks) } return node.AsNode() } func (node *TypeReferenceNode) ForEachChild(v Visitor) bool { - return visit(v, node.TypeName) || visitNodeList(v, node.TypeArguments) + return visit(v, node.TypeName()) || visitNodeList(v, node.TypeArguments()) } func (node *TypeReferenceNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateTypeReferenceNode(node, v.visitNode(node.TypeName), v.visitNodes(node.TypeArguments)) + return v.Factory.UpdateTypeReferenceNode(node, v.visitNode(node.TypeName()), v.visitNodes(node.TypeArguments())) } func (node *TypeReferenceNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewTypeReferenceNode(node.TypeName, node.TypeArguments), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewTypeReferenceNode(node.TypeName(), node.TypeArguments()), node.AsNode(), f.AsNodeFactory().hooks) } func IsTypeReferenceNode(node *Node) bool { @@ -5448,34 +6183,46 @@ func IsTypeReferenceNode(node *Node) bool { type ExpressionWithTypeArguments struct { MemberExpressionBase CompositeBase - Expression *Expression - TypeArguments *TypeList // Optional + expression link[Node] // *Expression + typeArguments link[NodeList] // *TypeList. Optional +} + +func (node *ExpressionWithTypeArguments) Expression() *Expression { return node.expression.get() } + +func (node *ExpressionWithTypeArguments) SetExpression(expression *Expression) { + node.expression.set(expression) +} + +func (node *ExpressionWithTypeArguments) TypeArguments() *TypeList { return node.typeArguments.get() } + +func (node *ExpressionWithTypeArguments) SetTypeArguments(typeArguments *TypeList) { + node.typeArguments.set(typeArguments) } func (f *NodeFactory) NewExpressionWithTypeArguments(expression *Expression, typeArguments *TypeList) *Node { - data := f.expressionWithTypeArgumentsArena.New() - data.Expression = expression - data.TypeArguments = typeArguments + data := newData[ExpressionWithTypeArguments](f) + data.expression.set(expression) + data.typeArguments.set(typeArguments) return f.newNode(KindExpressionWithTypeArguments, data) } func (f *NodeFactory) UpdateExpressionWithTypeArguments(node *ExpressionWithTypeArguments, expression *Expression, typeArguments *TypeList) *Node { - if expression != node.Expression || typeArguments != node.TypeArguments { + if expression != node.Expression() || typeArguments != node.TypeArguments() { return updateNode(f.NewExpressionWithTypeArguments(expression, typeArguments), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ExpressionWithTypeArguments) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) || visitNodeList(v, node.TypeArguments) + return visit(v, node.Expression()) || visitNodeList(v, node.TypeArguments()) } func (node *ExpressionWithTypeArguments) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateExpressionWithTypeArguments(node, v.visitNode(node.Expression), v.visitNodes(node.TypeArguments)) + return v.Factory.UpdateExpressionWithTypeArguments(node, v.visitNode(node.Expression()), v.visitNodes(node.TypeArguments())) } func (node *ExpressionWithTypeArguments) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewExpressionWithTypeArguments(node.Expression, node.TypeArguments), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewExpressionWithTypeArguments(node.Expression(), node.TypeArguments()), node.AsNode(), f.AsNodeFactory().hooks) } func IsExpressionWithTypeArguments(node *Node) bool { @@ -5488,32 +6235,36 @@ func IsExpressionWithTypeArguments(node *Node) bool { type LiteralTypeNode struct { TypeNodeBase - Literal *Node + literal link[Node] // *Node } +func (node *LiteralTypeNode) Literal() *Node { return node.literal.get() } + +func (node *LiteralTypeNode) SetLiteral(literal *Node) { node.literal.set(literal) } + func (f *NodeFactory) NewLiteralTypeNode(literal *Node) *Node { - data := f.literalTypeNodeArena.New() - data.Literal = literal + data := newData[LiteralTypeNode](f) + data.literal.set(literal) return f.newNode(KindLiteralType, data) } func (f *NodeFactory) UpdateLiteralTypeNode(node *LiteralTypeNode, literal *Node) *Node { - if literal != node.Literal { + if literal != node.Literal() { return updateNode(f.NewLiteralTypeNode(literal), node.AsNode(), f.hooks) } return node.AsNode() } func (node *LiteralTypeNode) ForEachChild(v Visitor) bool { - return visit(v, node.Literal) + return visit(v, node.Literal()) } func (node *LiteralTypeNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateLiteralTypeNode(node, v.visitNode(node.Literal)) + return v.Factory.UpdateLiteralTypeNode(node, v.visitNode(node.Literal())) } func (node *LiteralTypeNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewLiteralTypeNode(node.Literal), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewLiteralTypeNode(node.Literal()), node.AsNode(), f.AsNodeFactory().hooks) } func IsLiteralTypeNode(node *Node) bool { @@ -5529,7 +6280,7 @@ type ThisTypeNode struct { } func (f *NodeFactory) NewThisTypeNode() *Node { - data := &ThisTypeNode{} + data := newData[ThisTypeNode](f) return f.newNode(KindThisType, data) } @@ -5547,36 +6298,54 @@ func IsThisTypeNode(node *Node) bool { type TypePredicateNode struct { TypeNodeBase - AssertsModifier *AssertsKeyword // Optional - ParameterName *TypePredicateParameterName - Type *TypeNode // Optional + assertsModifier link[Node] // *AssertsKeyword. Optional + parameterName link[Node] // *TypePredicateParameterName + typeNode link[Node] // *TypeNode. Optional +} + +func (node *TypePredicateNode) AssertsModifier() *AssertsKeyword { return node.assertsModifier.get() } + +func (node *TypePredicateNode) SetAssertsModifier(assertsModifier *AssertsKeyword) { + node.assertsModifier.set(assertsModifier) +} + +func (node *TypePredicateNode) ParameterName() *TypePredicateParameterName { + return node.parameterName.get() } +func (node *TypePredicateNode) SetParameterName(parameterName *TypePredicateParameterName) { + node.parameterName.set(parameterName) +} + +func (node *TypePredicateNode) Type() *TypeNode { return node.typeNode.get() } + +func (node *TypePredicateNode) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + func (f *NodeFactory) NewTypePredicateNode(assertsModifier *AssertsKeyword, parameterName *TypePredicateParameterName, typeNode *TypeNode) *Node { - data := &TypePredicateNode{} - data.AssertsModifier = assertsModifier - data.ParameterName = parameterName - data.Type = typeNode + data := newData[TypePredicateNode](f) + data.assertsModifier.set(assertsModifier) + data.parameterName.set(parameterName) + data.typeNode.set(typeNode) return f.newNode(KindTypePredicate, data) } func (f *NodeFactory) UpdateTypePredicateNode(node *TypePredicateNode, assertsModifier *AssertsKeyword, parameterName *TypePredicateParameterName, typeNode *TypeNode) *Node { - if assertsModifier != node.AssertsModifier || parameterName != node.ParameterName || typeNode != node.Type { + if assertsModifier != node.AssertsModifier() || parameterName != node.ParameterName() || typeNode != node.Type() { return updateNode(f.NewTypePredicateNode(assertsModifier, parameterName, typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *TypePredicateNode) ForEachChild(v Visitor) bool { - return visit(v, node.AssertsModifier) || visit(v, node.ParameterName) || visit(v, node.Type) + return visit(v, node.AssertsModifier()) || visit(v, node.ParameterName()) || visit(v, node.Type()) } func (node *TypePredicateNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateTypePredicateNode(node, v.visitNode(node.AssertsModifier), v.visitNode(node.ParameterName), v.visitNode(node.Type)) + return v.Factory.UpdateTypePredicateNode(node, v.visitNode(node.AssertsModifier()), v.visitNode(node.ParameterName()), v.visitNode(node.Type())) } func (node *TypePredicateNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewTypePredicateNode(node.AssertsModifier, node.ParameterName, node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewTypePredicateNode(node.AssertsModifier(), node.ParameterName(), node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func IsTypePredicateNode(node *Node) bool { @@ -5590,43 +6359,47 @@ func IsTypePredicateNode(node *Node) bool { type ImportAttribute struct { NodeBase CompositeBase - name *ImportAttributeName - Value *Expression + name link[Node] // *ImportAttributeName + value link[Node] // *Expression } +func (node *ImportAttribute) Value() *Expression { return node.value.get() } + +func (node *ImportAttribute) SetValue(value *Expression) { node.value.set(value) } + func (f *NodeFactory) NewImportAttribute(name *ImportAttributeName, value *Expression) *Node { - data := &ImportAttribute{} - data.name = name - data.Value = value + data := newData[ImportAttribute](f) + data.name.set(name) + data.value.set(value) return f.newNode(KindImportAttribute, data) } func (f *NodeFactory) UpdateImportAttribute(node *ImportAttribute, name *ImportAttributeName, value *Expression) *Node { - if name != node.name || value != node.Value { + if name != node.name.get() || value != node.Value() { return updateNode(f.NewImportAttribute(name, value), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ImportAttribute) ForEachChild(v Visitor) bool { - return visit(v, node.name) || visit(v, node.Value) + return visit(v, node.name.get()) || visit(v, node.Value()) } func (node *ImportAttribute) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateImportAttribute(node, v.visitNode(node.name), v.visitNode(node.Value)) + return v.Factory.UpdateImportAttribute(node, v.visitNode(node.name.get()), v.visitNode(node.Value())) } func (node *ImportAttribute) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewImportAttribute(node.name, node.Value), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewImportAttribute(node.name.get(), node.Value()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ImportAttribute) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.name) | - propagateSubtreeFacts(node.Value) + return propagateSubtreeFacts(node.name.get()) | + propagateSubtreeFacts(node.Value()) } func (node *ImportAttribute) Name() *DeclarationName { - return node.name + return node.name.get() } func IsImportAttribute(node *Node) bool { @@ -5641,39 +6414,45 @@ type ImportAttributes struct { NodeBase CompositeBase Token Kind - Attributes *ImportAttributeList + attributes link[NodeList] // *ImportAttributeList MultiLine bool } +func (node *ImportAttributes) Attributes() *ImportAttributeList { return node.attributes.get() } + +func (node *ImportAttributes) SetAttributes(attributes *ImportAttributeList) { + node.attributes.set(attributes) +} + func (f *NodeFactory) NewImportAttributes(token Kind, attributes *ImportAttributeList, multiLine bool) *Node { - data := &ImportAttributes{} + data := newData[ImportAttributes](f) data.Token = token - data.Attributes = attributes + data.attributes.set(attributes) data.MultiLine = multiLine return f.newNode(KindImportAttributes, data) } func (f *NodeFactory) UpdateImportAttributes(node *ImportAttributes, token Kind, attributes *ImportAttributeList, multiLine bool) *Node { - if token != node.Token || attributes != node.Attributes || multiLine != node.MultiLine { + if token != node.Token || attributes != node.Attributes() || multiLine != node.MultiLine { return updateNode(f.NewImportAttributes(token, attributes, multiLine), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ImportAttributes) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.Attributes) + return visitNodeList(v, node.Attributes()) } func (node *ImportAttributes) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateImportAttributes(node, node.Token, v.visitNodes(node.Attributes), node.MultiLine) + return v.Factory.UpdateImportAttributes(node, node.Token, v.visitNodes(node.Attributes()), node.MultiLine) } func (node *ImportAttributes) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewImportAttributes(node.Token, node.Attributes, node.MultiLine), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewImportAttributes(node.Token, node.Attributes(), node.MultiLine), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ImportAttributes) computeSubtreeFacts() SubtreeFacts { - return propagateNodeListSubtreeFacts(node.Attributes, propagateSubtreeFacts) + return propagateNodeListSubtreeFacts(node.Attributes(), propagateSubtreeFacts) } func IsImportAttributes(node *Node) bool { @@ -5686,33 +6465,37 @@ func IsImportAttributes(node *Node) bool { type TypeQueryNode struct { NodeWithTypeArgumentsBase - ExprName *EntityName + exprName link[Node] // *EntityName } +func (node *TypeQueryNode) ExprName() *EntityName { return node.exprName.get() } + +func (node *TypeQueryNode) SetExprName(exprName *EntityName) { node.exprName.set(exprName) } + func (f *NodeFactory) NewTypeQueryNode(exprName *EntityName, typeArguments *TypeList) *Node { - data := &TypeQueryNode{} - data.ExprName = exprName - data.TypeArguments = typeArguments + data := newData[TypeQueryNode](f) + data.exprName.set(exprName) + data.typeArguments.set(typeArguments) return f.newNode(KindTypeQuery, data) } func (f *NodeFactory) UpdateTypeQueryNode(node *TypeQueryNode, exprName *EntityName, typeArguments *TypeList) *Node { - if exprName != node.ExprName || typeArguments != node.TypeArguments { + if exprName != node.ExprName() || typeArguments != node.TypeArguments() { return updateNode(f.NewTypeQueryNode(exprName, typeArguments), node.AsNode(), f.hooks) } return node.AsNode() } func (node *TypeQueryNode) ForEachChild(v Visitor) bool { - return visit(v, node.ExprName) || visitNodeList(v, node.TypeArguments) + return visit(v, node.ExprName()) || visitNodeList(v, node.TypeArguments()) } func (node *TypeQueryNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateTypeQueryNode(node, v.visitNode(node.ExprName), v.visitNodes(node.TypeArguments)) + return v.Factory.UpdateTypeQueryNode(node, v.visitNode(node.ExprName()), v.visitNodes(node.TypeArguments())) } func (node *TypeQueryNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewTypeQueryNode(node.ExprName, node.TypeArguments), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewTypeQueryNode(node.ExprName(), node.TypeArguments()), node.AsNode(), f.AsNodeFactory().hooks) } func IsTypeQueryNode(node *Node) bool { @@ -5727,47 +6510,79 @@ type MappedTypeNode struct { TypeNodeBase DeclarationBase LocalsContainerBase - ReadonlyToken *TokenNode // Optional - TypeParameter *TypeParameterDeclarationNode - NameType *TypeNode // Optional - QuestionToken *TokenNode // Optional - Type *TypeNode // Optional - Members *TypeElementList // Optional + readonlyToken link[Node] // *TokenNode. Optional + typeParameter link[Node] // *TypeParameterDeclarationNode + nameType link[Node] // *TypeNode. Optional + questionToken link[Node] // *TokenNode. Optional + typeNode link[Node] // *TypeNode. Optional + members link[NodeList] // *TypeElementList. Optional } +func (node *MappedTypeNode) ReadonlyToken() *TokenNode { return node.readonlyToken.get() } + +func (node *MappedTypeNode) SetReadonlyToken(readonlyToken *TokenNode) { + node.readonlyToken.set(readonlyToken) +} + +func (node *MappedTypeNode) TypeParameter() *TypeParameterDeclarationNode { + return node.typeParameter.get() +} + +func (node *MappedTypeNode) SetTypeParameter(typeParameter *TypeParameterDeclarationNode) { + node.typeParameter.set(typeParameter) +} + +func (node *MappedTypeNode) NameType() *TypeNode { return node.nameType.get() } + +func (node *MappedTypeNode) SetNameType(nameType *TypeNode) { node.nameType.set(nameType) } + +func (node *MappedTypeNode) QuestionToken() *TokenNode { return node.questionToken.get() } + +func (node *MappedTypeNode) SetQuestionToken(questionToken *TokenNode) { + node.questionToken.set(questionToken) +} + +func (node *MappedTypeNode) Type() *TypeNode { return node.typeNode.get() } + +func (node *MappedTypeNode) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + +func (node *MappedTypeNode) Members() *TypeElementList { return node.members.get() } + +func (node *MappedTypeNode) SetMembers(members *TypeElementList) { node.members.set(members) } + func (f *NodeFactory) NewMappedTypeNode(readonlyToken *TokenNode, typeParameter *TypeParameterDeclarationNode, nameType *TypeNode, questionToken *TokenNode, typeNode *TypeNode, members *TypeElementList) *Node { - data := &MappedTypeNode{} - data.ReadonlyToken = readonlyToken - data.TypeParameter = typeParameter - data.NameType = nameType - data.QuestionToken = questionToken - data.Type = typeNode - data.Members = members + data := newData[MappedTypeNode](f) + data.readonlyToken.set(readonlyToken) + data.typeParameter.set(typeParameter) + data.nameType.set(nameType) + data.questionToken.set(questionToken) + data.typeNode.set(typeNode) + data.members.set(members) return f.newNode(KindMappedType, data) } func (f *NodeFactory) UpdateMappedTypeNode(node *MappedTypeNode, readonlyToken *TokenNode, typeParameter *TypeParameterDeclarationNode, nameType *TypeNode, questionToken *TokenNode, typeNode *TypeNode, members *TypeElementList) *Node { - if readonlyToken != node.ReadonlyToken || typeParameter != node.TypeParameter || nameType != node.NameType || questionToken != node.QuestionToken || typeNode != node.Type || members != node.Members { + if readonlyToken != node.ReadonlyToken() || typeParameter != node.TypeParameter() || nameType != node.NameType() || questionToken != node.QuestionToken() || typeNode != node.Type() || members != node.Members() { return updateNode(f.NewMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, typeNode, members), node.AsNode(), f.hooks) } return node.AsNode() } func (node *MappedTypeNode) ForEachChild(v Visitor) bool { - return visit(v, node.ReadonlyToken) || - visit(v, node.TypeParameter) || - visit(v, node.NameType) || - visit(v, node.QuestionToken) || - visit(v, node.Type) || - visitNodeList(v, node.Members) + return visit(v, node.ReadonlyToken()) || + visit(v, node.TypeParameter()) || + visit(v, node.NameType()) || + visit(v, node.QuestionToken()) || + visit(v, node.Type()) || + visitNodeList(v, node.Members()) } func (node *MappedTypeNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateMappedTypeNode(node, v.visitNode(node.ReadonlyToken), v.visitNode(node.TypeParameter), v.visitNode(node.NameType), v.visitNode(node.QuestionToken), v.visitNode(node.Type), v.visitNodes(node.Members)) + return v.Factory.UpdateMappedTypeNode(node, v.visitNode(node.ReadonlyToken()), v.visitNode(node.TypeParameter()), v.visitNode(node.NameType()), v.visitNode(node.QuestionToken()), v.visitNode(node.Type()), v.visitNodes(node.Members())) } func (node *MappedTypeNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewMappedTypeNode(node.ReadonlyToken, node.TypeParameter, node.NameType, node.QuestionToken, node.Type, node.Members), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewMappedTypeNode(node.ReadonlyToken(), node.TypeParameter(), node.NameType(), node.QuestionToken(), node.Type(), node.Members()), node.AsNode(), f.AsNodeFactory().hooks) } func IsMappedTypeNode(node *Node) bool { @@ -5781,32 +6596,36 @@ func IsMappedTypeNode(node *Node) bool { type TypeLiteralNode struct { TypeNodeBase DeclarationBase - Members *TypeElementList + members link[NodeList] // *TypeElementList } +func (node *TypeLiteralNode) Members() *TypeElementList { return node.members.get() } + +func (node *TypeLiteralNode) SetMembers(members *TypeElementList) { node.members.set(members) } + func (f *NodeFactory) NewTypeLiteralNode(members *TypeElementList) *Node { - data := f.typeLiteralNodeArena.New() - data.Members = members + data := newData[TypeLiteralNode](f) + data.members.set(members) return f.newNode(KindTypeLiteral, data) } func (f *NodeFactory) UpdateTypeLiteralNode(node *TypeLiteralNode, members *TypeElementList) *Node { - if members != node.Members { + if members != node.Members() { return updateNode(f.NewTypeLiteralNode(members), node.AsNode(), f.hooks) } return node.AsNode() } func (node *TypeLiteralNode) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.Members) + return visitNodeList(v, node.Members()) } func (node *TypeLiteralNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateTypeLiteralNode(node, v.visitNodes(node.Members)) + return v.Factory.UpdateTypeLiteralNode(node, v.visitNodes(node.Members())) } func (node *TypeLiteralNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewTypeLiteralNode(node.Members), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewTypeLiteralNode(node.Members()), node.AsNode(), f.AsNodeFactory().hooks) } func IsTypeLiteralNode(node *Node) bool { @@ -5819,32 +6638,36 @@ func IsTypeLiteralNode(node *Node) bool { type TupleTypeNode struct { TypeNodeBase - Elements *TypeList + elements link[NodeList] // *TypeList } +func (node *TupleTypeNode) Elements() *TypeList { return node.elements.get() } + +func (node *TupleTypeNode) SetElements(elements *TypeList) { node.elements.set(elements) } + func (f *NodeFactory) NewTupleTypeNode(elements *TypeList) *Node { - data := &TupleTypeNode{} - data.Elements = elements + data := newData[TupleTypeNode](f) + data.elements.set(elements) return f.newNode(KindTupleType, data) } func (f *NodeFactory) UpdateTupleTypeNode(node *TupleTypeNode, elements *TypeList) *Node { - if elements != node.Elements { + if elements != node.Elements() { return updateNode(f.NewTupleTypeNode(elements), node.AsNode(), f.hooks) } return node.AsNode() } func (node *TupleTypeNode) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.Elements) + return visitNodeList(v, node.Elements()) } func (node *TupleTypeNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateTupleTypeNode(node, v.visitNodes(node.Elements)) + return v.Factory.UpdateTupleTypeNode(node, v.visitNodes(node.Elements())) } func (node *TupleTypeNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewTupleTypeNode(node.Elements), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewTupleTypeNode(node.Elements()), node.AsNode(), f.AsNodeFactory().hooks) } func IsTupleTypeNode(node *Node) bool { @@ -5858,45 +6681,61 @@ func IsTupleTypeNode(node *Node) bool { type NamedTupleMember struct { TypeNodeBase DeclarationBase - DotDotDotToken *DotDotDotToken // Optional - name *IdentifierNode - QuestionToken *QuestionToken // Optional - Type *TypeNode + dotDotDotToken link[Node] // *DotDotDotToken. Optional + name link[Node] // *IdentifierNode + questionToken link[Node] // *QuestionToken. Optional + typeNode link[Node] // *TypeNode } +func (node *NamedTupleMember) DotDotDotToken() *DotDotDotToken { return node.dotDotDotToken.get() } + +func (node *NamedTupleMember) SetDotDotDotToken(dotDotDotToken *DotDotDotToken) { + node.dotDotDotToken.set(dotDotDotToken) +} + +func (node *NamedTupleMember) QuestionToken() *QuestionToken { return node.questionToken.get() } + +func (node *NamedTupleMember) SetQuestionToken(questionToken *QuestionToken) { + node.questionToken.set(questionToken) +} + +func (node *NamedTupleMember) Type() *TypeNode { return node.typeNode.get() } + +func (node *NamedTupleMember) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + func (f *NodeFactory) NewNamedTupleMember(dotDotDotToken *DotDotDotToken, name *IdentifierNode, questionToken *QuestionToken, typeNode *TypeNode) *Node { - data := &NamedTupleMember{} - data.DotDotDotToken = dotDotDotToken - data.name = name - data.QuestionToken = questionToken - data.Type = typeNode + data := newData[NamedTupleMember](f) + data.dotDotDotToken.set(dotDotDotToken) + data.name.set(name) + data.questionToken.set(questionToken) + data.typeNode.set(typeNode) return f.newNode(KindNamedTupleMember, data) } func (f *NodeFactory) UpdateNamedTupleMember(node *NamedTupleMember, dotDotDotToken *DotDotDotToken, name *IdentifierNode, questionToken *QuestionToken, typeNode *TypeNode) *Node { - if dotDotDotToken != node.DotDotDotToken || name != node.name || questionToken != node.QuestionToken || typeNode != node.Type { + if dotDotDotToken != node.DotDotDotToken() || name != node.name.get() || questionToken != node.QuestionToken() || typeNode != node.Type() { return updateNode(f.NewNamedTupleMember(dotDotDotToken, name, questionToken, typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *NamedTupleMember) ForEachChild(v Visitor) bool { - return visit(v, node.DotDotDotToken) || - visit(v, node.name) || - visit(v, node.QuestionToken) || - visit(v, node.Type) + return visit(v, node.DotDotDotToken()) || + visit(v, node.name.get()) || + visit(v, node.QuestionToken()) || + visit(v, node.Type()) } func (node *NamedTupleMember) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateNamedTupleMember(node, v.visitNode(node.DotDotDotToken), v.visitNode(node.name), v.visitNode(node.QuestionToken), v.visitNode(node.Type)) + return v.Factory.UpdateNamedTupleMember(node, v.visitNode(node.DotDotDotToken()), v.visitNode(node.name.get()), v.visitNode(node.QuestionToken()), v.visitNode(node.Type())) } func (node *NamedTupleMember) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewNamedTupleMember(node.DotDotDotToken, node.name, node.QuestionToken, node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewNamedTupleMember(node.DotDotDotToken(), node.name.get(), node.QuestionToken(), node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *NamedTupleMember) Name() *DeclarationName { - return node.name + return node.name.get() } func IsNamedTupleMember(node *Node) bool { @@ -5909,32 +6748,36 @@ func IsNamedTupleMember(node *Node) bool { type OptionalTypeNode struct { TypeNodeBase - Type *TypeNode + typeNode link[Node] // *TypeNode } +func (node *OptionalTypeNode) Type() *TypeNode { return node.typeNode.get() } + +func (node *OptionalTypeNode) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + func (f *NodeFactory) NewOptionalTypeNode(typeNode *TypeNode) *Node { - data := &OptionalTypeNode{} - data.Type = typeNode + data := newData[OptionalTypeNode](f) + data.typeNode.set(typeNode) return f.newNode(KindOptionalType, data) } func (f *NodeFactory) UpdateOptionalTypeNode(node *OptionalTypeNode, typeNode *TypeNode) *Node { - if typeNode != node.Type { + if typeNode != node.Type() { return updateNode(f.NewOptionalTypeNode(typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *OptionalTypeNode) ForEachChild(v Visitor) bool { - return visit(v, node.Type) + return visit(v, node.Type()) } func (node *OptionalTypeNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateOptionalTypeNode(node, v.visitNode(node.Type)) + return v.Factory.UpdateOptionalTypeNode(node, v.visitNode(node.Type())) } func (node *OptionalTypeNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewOptionalTypeNode(node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewOptionalTypeNode(node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func IsOptionalTypeNode(node *Node) bool { @@ -5947,32 +6790,36 @@ func IsOptionalTypeNode(node *Node) bool { type RestTypeNode struct { TypeNodeBase - Type *TypeNode + typeNode link[Node] // *TypeNode } +func (node *RestTypeNode) Type() *TypeNode { return node.typeNode.get() } + +func (node *RestTypeNode) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + func (f *NodeFactory) NewRestTypeNode(typeNode *TypeNode) *Node { - data := &RestTypeNode{} - data.Type = typeNode + data := newData[RestTypeNode](f) + data.typeNode.set(typeNode) return f.newNode(KindRestType, data) } func (f *NodeFactory) UpdateRestTypeNode(node *RestTypeNode, typeNode *TypeNode) *Node { - if typeNode != node.Type { + if typeNode != node.Type() { return updateNode(f.NewRestTypeNode(typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *RestTypeNode) ForEachChild(v Visitor) bool { - return visit(v, node.Type) + return visit(v, node.Type()) } func (node *RestTypeNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateRestTypeNode(node, v.visitNode(node.Type)) + return v.Factory.UpdateRestTypeNode(node, v.visitNode(node.Type())) } func (node *RestTypeNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewRestTypeNode(node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewRestTypeNode(node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func IsRestTypeNode(node *Node) bool { @@ -5985,32 +6832,36 @@ func IsRestTypeNode(node *Node) bool { type ParenthesizedTypeNode struct { TypeNodeBase - Type *TypeNode + typeNode link[Node] // *TypeNode } +func (node *ParenthesizedTypeNode) Type() *TypeNode { return node.typeNode.get() } + +func (node *ParenthesizedTypeNode) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + func (f *NodeFactory) NewParenthesizedTypeNode(typeNode *TypeNode) *Node { - data := f.parenthesizedTypeNodeArena.New() - data.Type = typeNode + data := newData[ParenthesizedTypeNode](f) + data.typeNode.set(typeNode) return f.newNode(KindParenthesizedType, data) } func (f *NodeFactory) UpdateParenthesizedTypeNode(node *ParenthesizedTypeNode, typeNode *TypeNode) *Node { - if typeNode != node.Type { + if typeNode != node.Type() { return updateNode(f.NewParenthesizedTypeNode(typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ParenthesizedTypeNode) ForEachChild(v Visitor) bool { - return visit(v, node.Type) + return visit(v, node.Type()) } func (node *ParenthesizedTypeNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateParenthesizedTypeNode(node, v.visitNode(node.Type)) + return v.Factory.UpdateParenthesizedTypeNode(node, v.visitNode(node.Type())) } func (node *ParenthesizedTypeNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewParenthesizedTypeNode(node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewParenthesizedTypeNode(node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func IsParenthesizedTypeNode(node *Node) bool { @@ -6026,30 +6877,30 @@ type FunctionTypeNode struct { } func (f *NodeFactory) NewFunctionTypeNode(typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode) *Node { - data := f.functionTypeNodeArena.New() - data.TypeParameters = typeParameters - data.Parameters = parameters - data.Type = typeNode + data := newData[FunctionTypeNode](f) + data.typeParameters.set(typeParameters) + data.parameters.set(parameters) + data.typeNode.set(typeNode) return f.newNode(KindFunctionType, data) } func (f *NodeFactory) UpdateFunctionTypeNode(node *FunctionTypeNode, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode) *Node { - if typeParameters != node.TypeParameters || parameters != node.Parameters || typeNode != node.Type { + if typeParameters != node.TypeParameters() || parameters != node.Parameters() || typeNode != node.Type() { return updateNode(f.NewFunctionTypeNode(typeParameters, parameters, typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *FunctionTypeNode) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.TypeParameters) || visitNodeList(v, node.Parameters) || visit(v, node.Type) + return visitNodeList(v, node.TypeParameters()) || visitNodeList(v, node.Parameters()) || visit(v, node.Type()) } func (node *FunctionTypeNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateFunctionTypeNode(node, v.visitNodes(node.TypeParameters), v.visitNodes(node.Parameters), v.visitNode(node.Type)) + return v.Factory.UpdateFunctionTypeNode(node, v.visitNodes(node.TypeParameters()), v.visitNodes(node.Parameters()), v.visitNode(node.Type())) } func (node *FunctionTypeNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewFunctionTypeNode(node.TypeParameters, node.Parameters, node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewFunctionTypeNode(node.TypeParameters(), node.Parameters(), node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func IsFunctionTypeNode(node *Node) bool { @@ -6065,34 +6916,34 @@ type ConstructorTypeNode struct { } func (f *NodeFactory) NewConstructorTypeNode(modifiers *ModifierList, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode) *Node { - data := &ConstructorTypeNode{} - data.modifiers = modifiers - data.TypeParameters = typeParameters - data.Parameters = parameters - data.Type = typeNode + data := newData[ConstructorTypeNode](f) + data.modifiers.set(modifiers) + data.typeParameters.set(typeParameters) + data.parameters.set(parameters) + data.typeNode.set(typeNode) return f.newNode(KindConstructorType, data) } func (f *NodeFactory) UpdateConstructorTypeNode(node *ConstructorTypeNode, modifiers *ModifierList, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode) *Node { - if modifiers != node.modifiers || typeParameters != node.TypeParameters || parameters != node.Parameters || typeNode != node.Type { + if modifiers != node.modifiers.get() || typeParameters != node.TypeParameters() || parameters != node.Parameters() || typeNode != node.Type() { return updateNode(f.NewConstructorTypeNode(modifiers, typeParameters, parameters, typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ConstructorTypeNode) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visitNodeList(v, node.TypeParameters) || - visitNodeList(v, node.Parameters) || - visit(v, node.Type) + return visitModifiers(v, node.modifiers.get()) || + visitNodeList(v, node.TypeParameters()) || + visitNodeList(v, node.Parameters()) || + visit(v, node.Type()) } func (node *ConstructorTypeNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateConstructorTypeNode(node, v.visitModifiers(node.modifiers), v.visitNodes(node.TypeParameters), v.visitNodes(node.Parameters), v.visitNode(node.Type)) + return v.Factory.UpdateConstructorTypeNode(node, v.visitModifiers(node.modifiers.get()), v.visitNodes(node.TypeParameters()), v.visitNodes(node.Parameters()), v.visitNode(node.Type())) } func (node *ConstructorTypeNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewConstructorTypeNode(node.Modifiers(), node.TypeParameters, node.Parameters, node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewConstructorTypeNode(node.Modifiers(), node.TypeParameters(), node.Parameters(), node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func IsConstructorTypeNode(node *Node) bool { @@ -6109,9 +6960,11 @@ type TemplateHead struct { } func (f *NodeFactory) NewTemplateHead(text string, rawText string, templateFlags TokenFlags) *Node { - data := &TemplateHead{} + data := newData[TemplateHead](f) data.Text = text + f.keepString(text) data.RawText = rawText + f.keepString(rawText) data.TemplateFlags = templateFlags & TokenFlagsTemplateLiteralLikeFlags f.textCount++ return f.newNode(KindTemplateHead, data) @@ -6135,9 +6988,11 @@ type TemplateMiddle struct { } func (f *NodeFactory) NewTemplateMiddle(text string, rawText string, templateFlags TokenFlags) *Node { - data := &TemplateMiddle{} + data := newData[TemplateMiddle](f) data.Text = text + f.keepString(text) data.RawText = rawText + f.keepString(rawText) data.TemplateFlags = templateFlags & TokenFlagsTemplateLiteralLikeFlags f.textCount++ return f.newNode(KindTemplateMiddle, data) @@ -6161,9 +7016,11 @@ type TemplateTail struct { } func (f *NodeFactory) NewTemplateTail(text string, rawText string, templateFlags TokenFlags) *Node { - data := &TemplateTail{} + data := newData[TemplateTail](f) data.Text = text + f.keepString(text) data.RawText = rawText + f.keepString(rawText) data.TemplateFlags = templateFlags & TokenFlagsTemplateLiteralLikeFlags f.textCount++ return f.newNode(KindTemplateTail, data) @@ -6183,34 +7040,46 @@ func IsTemplateTail(node *Node) bool { type TemplateLiteralTypeNode struct { TypeNodeBase - Head *TemplateHeadNode - TemplateSpans *TemplateLiteralTypeSpanList + head link[Node] // *TemplateHeadNode + templateSpans link[NodeList] // *TemplateLiteralTypeSpanList +} + +func (node *TemplateLiteralTypeNode) Head() *TemplateHeadNode { return node.head.get() } + +func (node *TemplateLiteralTypeNode) SetHead(head *TemplateHeadNode) { node.head.set(head) } + +func (node *TemplateLiteralTypeNode) TemplateSpans() *TemplateLiteralTypeSpanList { + return node.templateSpans.get() +} + +func (node *TemplateLiteralTypeNode) SetTemplateSpans(templateSpans *TemplateLiteralTypeSpanList) { + node.templateSpans.set(templateSpans) } func (f *NodeFactory) NewTemplateLiteralTypeNode(head *TemplateHeadNode, templateSpans *TemplateLiteralTypeSpanList) *Node { - data := &TemplateLiteralTypeNode{} - data.Head = head - data.TemplateSpans = templateSpans + data := newData[TemplateLiteralTypeNode](f) + data.head.set(head) + data.templateSpans.set(templateSpans) return f.newNode(KindTemplateLiteralType, data) } func (f *NodeFactory) UpdateTemplateLiteralTypeNode(node *TemplateLiteralTypeNode, head *TemplateHeadNode, templateSpans *TemplateLiteralTypeSpanList) *Node { - if head != node.Head || templateSpans != node.TemplateSpans { + if head != node.Head() || templateSpans != node.TemplateSpans() { return updateNode(f.NewTemplateLiteralTypeNode(head, templateSpans), node.AsNode(), f.hooks) } return node.AsNode() } func (node *TemplateLiteralTypeNode) ForEachChild(v Visitor) bool { - return visit(v, node.Head) || visitNodeList(v, node.TemplateSpans) + return visit(v, node.Head()) || visitNodeList(v, node.TemplateSpans()) } func (node *TemplateLiteralTypeNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateTemplateLiteralTypeNode(node, v.visitNode(node.Head), v.visitNodes(node.TemplateSpans)) + return v.Factory.UpdateTemplateLiteralTypeNode(node, v.visitNode(node.Head()), v.visitNodes(node.TemplateSpans())) } func (node *TemplateLiteralTypeNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewTemplateLiteralTypeNode(node.Head, node.TemplateSpans), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewTemplateLiteralTypeNode(node.Head(), node.TemplateSpans()), node.AsNode(), f.AsNodeFactory().hooks) } func IsTemplateLiteralTypeNode(node *Node) bool { @@ -6223,34 +7092,44 @@ func IsTemplateLiteralTypeNode(node *Node) bool { type TemplateLiteralTypeSpan struct { TypeNodeBase - Type *TypeNode - Literal *TemplateMiddleOrTail + typeNode link[Node] // *TypeNode + literal link[Node] // *TemplateMiddleOrTail +} + +func (node *TemplateLiteralTypeSpan) Type() *TypeNode { return node.typeNode.get() } + +func (node *TemplateLiteralTypeSpan) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + +func (node *TemplateLiteralTypeSpan) Literal() *TemplateMiddleOrTail { return node.literal.get() } + +func (node *TemplateLiteralTypeSpan) SetLiteral(literal *TemplateMiddleOrTail) { + node.literal.set(literal) } func (f *NodeFactory) NewTemplateLiteralTypeSpan(typeNode *TypeNode, literal *TemplateMiddleOrTail) *Node { - data := &TemplateLiteralTypeSpan{} - data.Type = typeNode - data.Literal = literal + data := newData[TemplateLiteralTypeSpan](f) + data.typeNode.set(typeNode) + data.literal.set(literal) return f.newNode(KindTemplateLiteralTypeSpan, data) } func (f *NodeFactory) UpdateTemplateLiteralTypeSpan(node *TemplateLiteralTypeSpan, typeNode *TypeNode, literal *TemplateMiddleOrTail) *Node { - if typeNode != node.Type || literal != node.Literal { + if typeNode != node.Type() || literal != node.Literal() { return updateNode(f.NewTemplateLiteralTypeSpan(typeNode, literal), node.AsNode(), f.hooks) } return node.AsNode() } func (node *TemplateLiteralTypeSpan) ForEachChild(v Visitor) bool { - return visit(v, node.Type) || visit(v, node.Literal) + return visit(v, node.Type()) || visit(v, node.Literal()) } func (node *TemplateLiteralTypeSpan) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateTemplateLiteralTypeSpan(node, v.visitNode(node.Type), v.visitNode(node.Literal)) + return v.Factory.UpdateTemplateLiteralTypeSpan(node, v.visitNode(node.Type()), v.visitNode(node.Literal())) } func (node *TemplateLiteralTypeSpan) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewTemplateLiteralTypeSpan(node.Type, node.Literal), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewTemplateLiteralTypeSpan(node.Type(), node.Literal()), node.AsNode(), f.AsNodeFactory().hooks) } func IsTemplateLiteralTypeSpan(node *Node) bool { @@ -6265,34 +7144,41 @@ type SyntheticExpression struct { ExpressionBase Type any IsSpread bool - TupleNameSource *Node // Optional + tupleNameSource link[Node] // *Node. Optional +} + +func (node *SyntheticExpression) TupleNameSource() *Node { return node.tupleNameSource.get() } + +func (node *SyntheticExpression) SetTupleNameSource(tupleNameSource *Node) { + node.tupleNameSource.set(tupleNameSource) } func (f *NodeFactory) NewSyntheticExpression(typeNode any, isSpread bool, tupleNameSource *Node) *Node { - data := &SyntheticExpression{} + data := newData[SyntheticExpression](f) data.Type = typeNode + f.keepValue(typeNode) data.IsSpread = isSpread - data.TupleNameSource = tupleNameSource + data.tupleNameSource.set(tupleNameSource) return f.newNode(KindSyntheticExpression, data) } func (f *NodeFactory) UpdateSyntheticExpression(node *SyntheticExpression, typeNode any, isSpread bool, tupleNameSource *Node) *Node { - if typeNode != node.Type || isSpread != node.IsSpread || tupleNameSource != node.TupleNameSource { + if typeNode != node.Type || isSpread != node.IsSpread || tupleNameSource != node.TupleNameSource() { return updateNode(f.NewSyntheticExpression(typeNode, isSpread, tupleNameSource), node.AsNode(), f.hooks) } return node.AsNode() } func (node *SyntheticExpression) ForEachChild(v Visitor) bool { - return visit(v, node.TupleNameSource) + return visit(v, node.TupleNameSource()) } func (node *SyntheticExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateSyntheticExpression(node, node.Type, node.IsSpread, v.visitNode(node.TupleNameSource)) + return v.Factory.UpdateSyntheticExpression(node, node.Type, node.IsSpread, v.visitNode(node.TupleNameSource())) } func (node *SyntheticExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewSyntheticExpression(node.Type, node.IsSpread, node.TupleNameSource), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewSyntheticExpression(node.Type, node.IsSpread, node.TupleNameSource()), node.AsNode(), f.AsNodeFactory().hooks) } func IsSyntheticExpression(node *Node) bool { @@ -6305,36 +7191,42 @@ func IsSyntheticExpression(node *Node) bool { type PartiallyEmittedExpression struct { LeftHandSideExpressionBase - Expression *Expression + expression link[Node] // *Expression +} + +func (node *PartiallyEmittedExpression) Expression() *Expression { return node.expression.get() } + +func (node *PartiallyEmittedExpression) SetExpression(expression *Expression) { + node.expression.set(expression) } func (f *NodeFactory) NewPartiallyEmittedExpression(expression *Expression) *Node { - data := &PartiallyEmittedExpression{} - data.Expression = expression + data := newData[PartiallyEmittedExpression](f) + data.expression.set(expression) return f.newNode(KindPartiallyEmittedExpression, data) } func (f *NodeFactory) UpdatePartiallyEmittedExpression(node *PartiallyEmittedExpression, expression *Expression) *Node { - if expression != node.Expression { + if expression != node.Expression() { return updateNode(f.NewPartiallyEmittedExpression(expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *PartiallyEmittedExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) + return visit(v, node.Expression()) } func (node *PartiallyEmittedExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdatePartiallyEmittedExpression(node, v.visitNode(node.Expression)) + return v.Factory.UpdatePartiallyEmittedExpression(node, v.visitNode(node.Expression())) } func (node *PartiallyEmittedExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewPartiallyEmittedExpression(node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewPartiallyEmittedExpression(node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *PartiallyEmittedExpression) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) + return propagateSubtreeFacts(node.Expression()) } func IsPartiallyEmittedExpression(node *Node) bool { @@ -6348,36 +7240,52 @@ func IsPartiallyEmittedExpression(node *Node) bool { type JsxElement struct { PrimaryExpressionBase CompositeBase - OpeningElement *JsxOpeningElementNode - Children *JsxChildList - ClosingElement *JsxClosingElementNode + openingElement link[Node] // *JsxOpeningElementNode + children link[NodeList] // *JsxChildList + closingElement link[Node] // *JsxClosingElementNode +} + +func (node *JsxElement) OpeningElement() *JsxOpeningElementNode { return node.openingElement.get() } + +func (node *JsxElement) SetOpeningElement(openingElement *JsxOpeningElementNode) { + node.openingElement.set(openingElement) +} + +func (node *JsxElement) Children() *JsxChildList { return node.children.get() } + +func (node *JsxElement) SetChildren(children *JsxChildList) { node.children.set(children) } + +func (node *JsxElement) ClosingElement() *JsxClosingElementNode { return node.closingElement.get() } + +func (node *JsxElement) SetClosingElement(closingElement *JsxClosingElementNode) { + node.closingElement.set(closingElement) } func (f *NodeFactory) NewJsxElement(openingElement *JsxOpeningElementNode, children *JsxChildList, closingElement *JsxClosingElementNode) *Node { - data := &JsxElement{} - data.OpeningElement = openingElement - data.Children = children - data.ClosingElement = closingElement + data := newData[JsxElement](f) + data.openingElement.set(openingElement) + data.children.set(children) + data.closingElement.set(closingElement) return f.newNode(KindJsxElement, data) } func (f *NodeFactory) UpdateJsxElement(node *JsxElement, openingElement *JsxOpeningElementNode, children *JsxChildList, closingElement *JsxClosingElementNode) *Node { - if openingElement != node.OpeningElement || children != node.Children || closingElement != node.ClosingElement { + if openingElement != node.OpeningElement() || children != node.Children() || closingElement != node.ClosingElement() { return updateNode(f.NewJsxElement(openingElement, children, closingElement), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JsxElement) ForEachChild(v Visitor) bool { - return visit(v, node.OpeningElement) || visitNodeList(v, node.Children) || visit(v, node.ClosingElement) + return visit(v, node.OpeningElement()) || visitNodeList(v, node.Children()) || visit(v, node.ClosingElement()) } func (node *JsxElement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJsxElement(node, v.visitNode(node.OpeningElement), v.visitNodes(node.Children), v.visitNode(node.ClosingElement)) + return v.Factory.UpdateJsxElement(node, v.visitNode(node.OpeningElement()), v.visitNodes(node.Children()), v.visitNode(node.ClosingElement())) } func (node *JsxElement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJsxElement(node.OpeningElement, node.Children, node.ClosingElement), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJsxElement(node.OpeningElement(), node.Children(), node.ClosingElement()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJsxElement(node *Node) bool { @@ -6392,32 +7300,38 @@ type JsxAttributes struct { PrimaryExpressionBase DeclarationBase CompositeBase - Properties *JsxAttributeList + properties link[NodeList] // *JsxAttributeList +} + +func (node *JsxAttributes) Properties() *JsxAttributeList { return node.properties.get() } + +func (node *JsxAttributes) SetProperties(properties *JsxAttributeList) { + node.properties.set(properties) } func (f *NodeFactory) NewJsxAttributes(properties *JsxAttributeList) *Node { - data := &JsxAttributes{} - data.Properties = properties + data := newData[JsxAttributes](f) + data.properties.set(properties) return f.newNode(KindJsxAttributes, data) } func (f *NodeFactory) UpdateJsxAttributes(node *JsxAttributes, properties *JsxAttributeList) *Node { - if properties != node.Properties { + if properties != node.Properties() { return updateNode(f.NewJsxAttributes(properties), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JsxAttributes) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.Properties) + return visitNodeList(v, node.Properties()) } func (node *JsxAttributes) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJsxAttributes(node, v.visitNodes(node.Properties)) + return v.Factory.UpdateJsxAttributes(node, v.visitNodes(node.Properties())) } func (node *JsxAttributes) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJsxAttributes(node.Properties), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJsxAttributes(node.Properties()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJsxAttributes(node *Node) bool { @@ -6431,38 +7345,42 @@ func IsJsxAttributes(node *Node) bool { type JsxNamespacedName struct { ExpressionBase CompositeBase - Namespace *IdentifierNode - name *IdentifierNode + namespace link[Node] // *IdentifierNode + name link[Node] // *IdentifierNode } +func (node *JsxNamespacedName) Namespace() *IdentifierNode { return node.namespace.get() } + +func (node *JsxNamespacedName) SetNamespace(namespace *IdentifierNode) { node.namespace.set(namespace) } + func (f *NodeFactory) NewJsxNamespacedName(namespace *IdentifierNode, name *IdentifierNode) *Node { - data := &JsxNamespacedName{} - data.Namespace = namespace - data.name = name + data := newData[JsxNamespacedName](f) + data.namespace.set(namespace) + data.name.set(name) return f.newNode(KindJsxNamespacedName, data) } func (f *NodeFactory) UpdateJsxNamespacedName(node *JsxNamespacedName, namespace *IdentifierNode, name *IdentifierNode) *Node { - if namespace != node.Namespace || name != node.name { + if namespace != node.Namespace() || name != node.name.get() { return updateNode(f.NewJsxNamespacedName(namespace, name), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JsxNamespacedName) ForEachChild(v Visitor) bool { - return visit(v, node.Namespace) || visit(v, node.name) + return visit(v, node.Namespace()) || visit(v, node.name.get()) } func (node *JsxNamespacedName) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJsxNamespacedName(node, v.visitNode(node.Namespace), v.visitNode(node.name)) + return v.Factory.UpdateJsxNamespacedName(node, v.visitNode(node.Namespace()), v.visitNode(node.name.get())) } func (node *JsxNamespacedName) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJsxNamespacedName(node.Namespace, node.name), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJsxNamespacedName(node.Namespace(), node.name.get()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *JsxNamespacedName) Name() *DeclarationName { - return node.name + return node.name.get() } func IsJsxNamespacedName(node *Node) bool { @@ -6476,36 +7394,52 @@ func IsJsxNamespacedName(node *Node) bool { type JsxOpeningElement struct { ExpressionBase CompositeBase - TagName *JsxTagNameExpression - TypeArguments *TypeList // Optional - Attributes *JsxAttributesNode + tagName link[Node] // *JsxTagNameExpression + typeArguments link[NodeList] // *TypeList. Optional + attributes link[Node] // *JsxAttributesNode +} + +func (node *JsxOpeningElement) TagName() *JsxTagNameExpression { return node.tagName.get() } + +func (node *JsxOpeningElement) SetTagName(tagName *JsxTagNameExpression) { node.tagName.set(tagName) } + +func (node *JsxOpeningElement) TypeArguments() *TypeList { return node.typeArguments.get() } + +func (node *JsxOpeningElement) SetTypeArguments(typeArguments *TypeList) { + node.typeArguments.set(typeArguments) +} + +func (node *JsxOpeningElement) Attributes() *JsxAttributesNode { return node.attributes.get() } + +func (node *JsxOpeningElement) SetAttributes(attributes *JsxAttributesNode) { + node.attributes.set(attributes) } func (f *NodeFactory) NewJsxOpeningElement(tagName *JsxTagNameExpression, typeArguments *TypeList, attributes *JsxAttributesNode) *Node { - data := &JsxOpeningElement{} - data.TagName = tagName - data.TypeArguments = typeArguments - data.Attributes = attributes + data := newData[JsxOpeningElement](f) + data.tagName.set(tagName) + data.typeArguments.set(typeArguments) + data.attributes.set(attributes) return f.newNode(KindJsxOpeningElement, data) } func (f *NodeFactory) UpdateJsxOpeningElement(node *JsxOpeningElement, tagName *JsxTagNameExpression, typeArguments *TypeList, attributes *JsxAttributesNode) *Node { - if tagName != node.TagName || typeArguments != node.TypeArguments || attributes != node.Attributes { + if tagName != node.TagName() || typeArguments != node.TypeArguments() || attributes != node.Attributes() { return updateNode(f.NewJsxOpeningElement(tagName, typeArguments, attributes), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JsxOpeningElement) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || visitNodeList(v, node.TypeArguments) || visit(v, node.Attributes) + return visit(v, node.TagName()) || visitNodeList(v, node.TypeArguments()) || visit(v, node.Attributes()) } func (node *JsxOpeningElement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJsxOpeningElement(node, v.visitNode(node.TagName), v.visitNodes(node.TypeArguments), v.visitNode(node.Attributes)) + return v.Factory.UpdateJsxOpeningElement(node, v.visitNode(node.TagName()), v.visitNodes(node.TypeArguments()), v.visitNode(node.Attributes())) } func (node *JsxOpeningElement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJsxOpeningElement(node.TagName, node.TypeArguments, node.Attributes), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJsxOpeningElement(node.TagName(), node.TypeArguments(), node.Attributes()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJsxOpeningElement(node *Node) bool { @@ -6519,36 +7453,54 @@ func IsJsxOpeningElement(node *Node) bool { type JsxSelfClosingElement struct { PrimaryExpressionBase CompositeBase - TagName *JsxTagNameExpression - TypeArguments *TypeList // Optional - Attributes *JsxAttributesNode + tagName link[Node] // *JsxTagNameExpression + typeArguments link[NodeList] // *TypeList. Optional + attributes link[Node] // *JsxAttributesNode +} + +func (node *JsxSelfClosingElement) TagName() *JsxTagNameExpression { return node.tagName.get() } + +func (node *JsxSelfClosingElement) SetTagName(tagName *JsxTagNameExpression) { + node.tagName.set(tagName) +} + +func (node *JsxSelfClosingElement) TypeArguments() *TypeList { return node.typeArguments.get() } + +func (node *JsxSelfClosingElement) SetTypeArguments(typeArguments *TypeList) { + node.typeArguments.set(typeArguments) +} + +func (node *JsxSelfClosingElement) Attributes() *JsxAttributesNode { return node.attributes.get() } + +func (node *JsxSelfClosingElement) SetAttributes(attributes *JsxAttributesNode) { + node.attributes.set(attributes) } func (f *NodeFactory) NewJsxSelfClosingElement(tagName *JsxTagNameExpression, typeArguments *TypeList, attributes *JsxAttributesNode) *Node { - data := &JsxSelfClosingElement{} - data.TagName = tagName - data.TypeArguments = typeArguments - data.Attributes = attributes + data := newData[JsxSelfClosingElement](f) + data.tagName.set(tagName) + data.typeArguments.set(typeArguments) + data.attributes.set(attributes) return f.newNode(KindJsxSelfClosingElement, data) } func (f *NodeFactory) UpdateJsxSelfClosingElement(node *JsxSelfClosingElement, tagName *JsxTagNameExpression, typeArguments *TypeList, attributes *JsxAttributesNode) *Node { - if tagName != node.TagName || typeArguments != node.TypeArguments || attributes != node.Attributes { + if tagName != node.TagName() || typeArguments != node.TypeArguments() || attributes != node.Attributes() { return updateNode(f.NewJsxSelfClosingElement(tagName, typeArguments, attributes), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JsxSelfClosingElement) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || visitNodeList(v, node.TypeArguments) || visit(v, node.Attributes) + return visit(v, node.TagName()) || visitNodeList(v, node.TypeArguments()) || visit(v, node.Attributes()) } func (node *JsxSelfClosingElement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJsxSelfClosingElement(node, v.visitNode(node.TagName), v.visitNodes(node.TypeArguments), v.visitNode(node.Attributes)) + return v.Factory.UpdateJsxSelfClosingElement(node, v.visitNode(node.TagName()), v.visitNodes(node.TypeArguments()), v.visitNode(node.Attributes())) } func (node *JsxSelfClosingElement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJsxSelfClosingElement(node.TagName, node.TypeArguments, node.Attributes), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJsxSelfClosingElement(node.TagName(), node.TypeArguments(), node.Attributes()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJsxSelfClosingElement(node *Node) bool { @@ -6562,36 +7514,52 @@ func IsJsxSelfClosingElement(node *Node) bool { type JsxFragment struct { PrimaryExpressionBase CompositeBase - OpeningFragment *JsxOpeningFragmentNode - Children *JsxChildList - ClosingFragment *JsxClosingFragmentNode + openingFragment link[Node] // *JsxOpeningFragmentNode + children link[NodeList] // *JsxChildList + closingFragment link[Node] // *JsxClosingFragmentNode +} + +func (node *JsxFragment) OpeningFragment() *JsxOpeningFragmentNode { return node.openingFragment.get() } + +func (node *JsxFragment) SetOpeningFragment(openingFragment *JsxOpeningFragmentNode) { + node.openingFragment.set(openingFragment) +} + +func (node *JsxFragment) Children() *JsxChildList { return node.children.get() } + +func (node *JsxFragment) SetChildren(children *JsxChildList) { node.children.set(children) } + +func (node *JsxFragment) ClosingFragment() *JsxClosingFragmentNode { return node.closingFragment.get() } + +func (node *JsxFragment) SetClosingFragment(closingFragment *JsxClosingFragmentNode) { + node.closingFragment.set(closingFragment) } func (f *NodeFactory) NewJsxFragment(openingFragment *JsxOpeningFragmentNode, children *JsxChildList, closingFragment *JsxClosingFragmentNode) *Node { - data := &JsxFragment{} - data.OpeningFragment = openingFragment - data.Children = children - data.ClosingFragment = closingFragment + data := newData[JsxFragment](f) + data.openingFragment.set(openingFragment) + data.children.set(children) + data.closingFragment.set(closingFragment) return f.newNode(KindJsxFragment, data) } func (f *NodeFactory) UpdateJsxFragment(node *JsxFragment, openingFragment *JsxOpeningFragmentNode, children *JsxChildList, closingFragment *JsxClosingFragmentNode) *Node { - if openingFragment != node.OpeningFragment || children != node.Children || closingFragment != node.ClosingFragment { + if openingFragment != node.OpeningFragment() || children != node.Children() || closingFragment != node.ClosingFragment() { return updateNode(f.NewJsxFragment(openingFragment, children, closingFragment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JsxFragment) ForEachChild(v Visitor) bool { - return visit(v, node.OpeningFragment) || visitNodeList(v, node.Children) || visit(v, node.ClosingFragment) + return visit(v, node.OpeningFragment()) || visitNodeList(v, node.Children()) || visit(v, node.ClosingFragment()) } func (node *JsxFragment) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJsxFragment(node, v.visitNode(node.OpeningFragment), v.visitNodes(node.Children), v.visitNode(node.ClosingFragment)) + return v.Factory.UpdateJsxFragment(node, v.visitNode(node.OpeningFragment()), v.visitNodes(node.Children()), v.visitNode(node.ClosingFragment())) } func (node *JsxFragment) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJsxFragment(node.OpeningFragment, node.Children, node.ClosingFragment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJsxFragment(node.OpeningFragment(), node.Children(), node.ClosingFragment()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJsxFragment(node *Node) bool { @@ -6607,7 +7575,7 @@ type JsxOpeningFragment struct { } func (f *NodeFactory) NewJsxOpeningFragment() *Node { - data := &JsxOpeningFragment{} + data := newData[JsxOpeningFragment](f) return f.newNode(KindJsxOpeningFragment, data) } @@ -6628,7 +7596,7 @@ type JsxClosingFragment struct { } func (f *NodeFactory) NewJsxClosingFragment() *Node { - data := &JsxClosingFragment{} + data := newData[JsxClosingFragment](f) return f.newNode(KindJsxClosingFragment, data) } @@ -6648,38 +7616,44 @@ type JsxAttribute struct { NodeBase DeclarationBase CompositeBase - name *JsxAttributeName - Initializer *JsxAttributeValue // Optional + name link[Node] // *JsxAttributeName + initializer link[Node] // *JsxAttributeValue. Optional +} + +func (node *JsxAttribute) Initializer() *JsxAttributeValue { return node.initializer.get() } + +func (node *JsxAttribute) SetInitializer(initializer *JsxAttributeValue) { + node.initializer.set(initializer) } func (f *NodeFactory) NewJsxAttribute(name *JsxAttributeName, initializer *JsxAttributeValue) *Node { - data := &JsxAttribute{} - data.name = name - data.Initializer = initializer + data := newData[JsxAttribute](f) + data.name.set(name) + data.initializer.set(initializer) return f.newNode(KindJsxAttribute, data) } func (f *NodeFactory) UpdateJsxAttribute(node *JsxAttribute, name *JsxAttributeName, initializer *JsxAttributeValue) *Node { - if name != node.name || initializer != node.Initializer { + if name != node.name.get() || initializer != node.Initializer() { return updateNode(f.NewJsxAttribute(name, initializer), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JsxAttribute) ForEachChild(v Visitor) bool { - return visit(v, node.name) || visit(v, node.Initializer) + return visit(v, node.name.get()) || visit(v, node.Initializer()) } func (node *JsxAttribute) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJsxAttribute(node, v.visitNode(node.name), v.visitNode(node.Initializer)) + return v.Factory.UpdateJsxAttribute(node, v.visitNode(node.name.get()), v.visitNode(node.Initializer())) } func (node *JsxAttribute) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJsxAttribute(node.name, node.Initializer), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJsxAttribute(node.name.get(), node.Initializer()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *JsxAttribute) Name() *DeclarationName { - return node.name + return node.name.get() } func IsJsxAttribute(node *Node) bool { @@ -6694,32 +7668,38 @@ type JsxSpreadAttribute struct { ObjectLiteralElementBase NodeBase DeclarationBase - Expression *Expression + expression link[Node] // *Expression +} + +func (node *JsxSpreadAttribute) Expression() *Expression { return node.expression.get() } + +func (node *JsxSpreadAttribute) SetExpression(expression *Expression) { + node.expression.set(expression) } func (f *NodeFactory) NewJsxSpreadAttribute(expression *Expression) *Node { - data := &JsxSpreadAttribute{} - data.Expression = expression + data := newData[JsxSpreadAttribute](f) + data.expression.set(expression) return f.newNode(KindJsxSpreadAttribute, data) } func (f *NodeFactory) UpdateJsxSpreadAttribute(node *JsxSpreadAttribute, expression *Expression) *Node { - if expression != node.Expression { + if expression != node.Expression() { return updateNode(f.NewJsxSpreadAttribute(expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JsxSpreadAttribute) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) + return visit(v, node.Expression()) } func (node *JsxSpreadAttribute) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJsxSpreadAttribute(node, v.visitNode(node.Expression)) + return v.Factory.UpdateJsxSpreadAttribute(node, v.visitNode(node.Expression())) } func (node *JsxSpreadAttribute) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJsxSpreadAttribute(node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJsxSpreadAttribute(node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJsxSpreadAttribute(node *Node) bool { @@ -6732,32 +7712,36 @@ func IsJsxSpreadAttribute(node *Node) bool { type JsxClosingElement struct { NodeBase - TagName *JsxTagNameExpression + tagName link[Node] // *JsxTagNameExpression } +func (node *JsxClosingElement) TagName() *JsxTagNameExpression { return node.tagName.get() } + +func (node *JsxClosingElement) SetTagName(tagName *JsxTagNameExpression) { node.tagName.set(tagName) } + func (f *NodeFactory) NewJsxClosingElement(tagName *JsxTagNameExpression) *Node { - data := &JsxClosingElement{} - data.TagName = tagName + data := newData[JsxClosingElement](f) + data.tagName.set(tagName) return f.newNode(KindJsxClosingElement, data) } func (f *NodeFactory) UpdateJsxClosingElement(node *JsxClosingElement, tagName *JsxTagNameExpression) *Node { - if tagName != node.TagName { + if tagName != node.TagName() { return updateNode(f.NewJsxClosingElement(tagName), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JsxClosingElement) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) + return visit(v, node.TagName()) } func (node *JsxClosingElement) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJsxClosingElement(node, v.visitNode(node.TagName)) + return v.Factory.UpdateJsxClosingElement(node, v.visitNode(node.TagName())) } func (node *JsxClosingElement) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJsxClosingElement(node.TagName), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJsxClosingElement(node.TagName()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJsxClosingElement(node *Node) bool { @@ -6770,34 +7754,44 @@ func IsJsxClosingElement(node *Node) bool { type JsxExpression struct { ExpressionBase - DotDotDotToken *DotDotDotToken // Optional - Expression *Expression // Optional + dotDotDotToken link[Node] // *DotDotDotToken. Optional + expression link[Node] // *Expression. Optional } +func (node *JsxExpression) DotDotDotToken() *DotDotDotToken { return node.dotDotDotToken.get() } + +func (node *JsxExpression) SetDotDotDotToken(dotDotDotToken *DotDotDotToken) { + node.dotDotDotToken.set(dotDotDotToken) +} + +func (node *JsxExpression) Expression() *Expression { return node.expression.get() } + +func (node *JsxExpression) SetExpression(expression *Expression) { node.expression.set(expression) } + func (f *NodeFactory) NewJsxExpression(dotDotDotToken *DotDotDotToken, expression *Expression) *Node { - data := &JsxExpression{} - data.DotDotDotToken = dotDotDotToken - data.Expression = expression + data := newData[JsxExpression](f) + data.dotDotDotToken.set(dotDotDotToken) + data.expression.set(expression) return f.newNode(KindJsxExpression, data) } func (f *NodeFactory) UpdateJsxExpression(node *JsxExpression, dotDotDotToken *DotDotDotToken, expression *Expression) *Node { - if dotDotDotToken != node.DotDotDotToken || expression != node.Expression { + if dotDotDotToken != node.DotDotDotToken() || expression != node.Expression() { return updateNode(f.NewJsxExpression(dotDotDotToken, expression), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JsxExpression) ForEachChild(v Visitor) bool { - return visit(v, node.DotDotDotToken) || visit(v, node.Expression) + return visit(v, node.DotDotDotToken()) || visit(v, node.Expression()) } func (node *JsxExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJsxExpression(node, v.visitNode(node.DotDotDotToken), v.visitNode(node.Expression)) + return v.Factory.UpdateJsxExpression(node, v.visitNode(node.DotDotDotToken()), v.visitNode(node.Expression())) } func (node *JsxExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJsxExpression(node.DotDotDotToken, node.Expression), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJsxExpression(node.DotDotDotToken(), node.Expression()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJsxExpression(node *Node) bool { @@ -6815,8 +7809,9 @@ type JsxText struct { } func (f *NodeFactory) NewJsxText(text string, containsOnlyTriviaWhiteSpaces bool) *Node { - data := &JsxText{} + data := newData[JsxText](f) data.Text = text + f.keepString(text) data.ContainsOnlyTriviaWhiteSpaces = containsOnlyTriviaWhiteSpaces f.textCount++ return f.newNode(KindJsxText, data) @@ -6840,8 +7835,9 @@ type SyntaxList struct { } func (f *NodeFactory) NewSyntaxList(children []*Node) *Node { - data := &SyntaxList{} + data := newData[SyntaxList](f) data.Children = children + f.keepNodes(children) return f.newNode(KindSyntaxList, data) } @@ -6875,34 +7871,42 @@ func IsSyntaxList(node *Node) bool { type JSDoc struct { NodeBase - Comment *NodeList - Tags *NodeList // Optional + comment link[NodeList] // *NodeList + tags link[NodeList] // *NodeList. Optional } +func (node *JSDoc) Comment() *NodeList { return node.comment.get() } + +func (node *JSDoc) SetComment(comment *NodeList) { node.comment.set(comment) } + +func (node *JSDoc) Tags() *NodeList { return node.tags.get() } + +func (node *JSDoc) SetTags(tags *NodeList) { node.tags.set(tags) } + func (f *NodeFactory) NewJSDoc(comment *NodeList, tags *NodeList) *Node { - data := f.jsdocArena.New() - data.Comment = comment - data.Tags = tags + data := newData[JSDoc](f) + data.comment.set(comment) + data.tags.set(tags) return f.newNode(KindJSDoc, data) } func (f *NodeFactory) UpdateJSDoc(node *JSDoc, comment *NodeList, tags *NodeList) *Node { - if comment != node.Comment || tags != node.Tags { + if comment != node.Comment() || tags != node.Tags() { return updateNode(f.NewJSDoc(comment, tags), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDoc) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.Comment) || visitNodeList(v, node.Tags) + return visitNodeList(v, node.Comment()) || visitNodeList(v, node.Tags()) } func (node *JSDoc) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDoc(node, v.visitNodes(node.Comment), v.visitNodes(node.Tags)) + return v.Factory.UpdateJSDoc(node, v.visitNodes(node.Comment()), v.visitNodes(node.Tags())) } func (node *JSDoc) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDoc(node.Comment, node.Tags), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDoc(node.Comment(), node.Tags()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDoc(node *Node) bool { @@ -6915,32 +7919,36 @@ func IsJSDoc(node *Node) bool { type JSDocTypeExpression struct { TypeNodeBase - Type *TypeNode + typeNode link[Node] // *TypeNode } +func (node *JSDocTypeExpression) Type() *TypeNode { return node.typeNode.get() } + +func (node *JSDocTypeExpression) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + func (f *NodeFactory) NewJSDocTypeExpression(typeNode *TypeNode) *Node { - data := &JSDocTypeExpression{} - data.Type = typeNode + data := newData[JSDocTypeExpression](f) + data.typeNode.set(typeNode) return f.newNode(KindJSDocTypeExpression, data) } func (f *NodeFactory) UpdateJSDocTypeExpression(node *JSDocTypeExpression, typeNode *TypeNode) *Node { - if typeNode != node.Type { + if typeNode != node.Type() { return updateNode(f.NewJSDocTypeExpression(typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocTypeExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Type) + return visit(v, node.Type()) } func (node *JSDocTypeExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocTypeExpression(node, v.visitNode(node.Type)) + return v.Factory.UpdateJSDocTypeExpression(node, v.visitNode(node.Type())) } func (node *JSDocTypeExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocTypeExpression(node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocTypeExpression(node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocTypeExpression(node *Node) bool { @@ -6953,32 +7961,36 @@ func IsJSDocTypeExpression(node *Node) bool { type JSDocNonNullableType struct { JSDocTypeBase - Type *TypeNode + typeNode link[Node] // *TypeNode } +func (node *JSDocNonNullableType) Type() *TypeNode { return node.typeNode.get() } + +func (node *JSDocNonNullableType) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + func (f *NodeFactory) NewJSDocNonNullableType(typeNode *TypeNode) *Node { - data := &JSDocNonNullableType{} - data.Type = typeNode + data := newData[JSDocNonNullableType](f) + data.typeNode.set(typeNode) return f.newNode(KindJSDocNonNullableType, data) } func (f *NodeFactory) UpdateJSDocNonNullableType(node *JSDocNonNullableType, typeNode *TypeNode) *Node { - if typeNode != node.Type { + if typeNode != node.Type() { return updateNode(f.NewJSDocNonNullableType(typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocNonNullableType) ForEachChild(v Visitor) bool { - return visit(v, node.Type) + return visit(v, node.Type()) } func (node *JSDocNonNullableType) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocNonNullableType(node, v.visitNode(node.Type)) + return v.Factory.UpdateJSDocNonNullableType(node, v.visitNode(node.Type())) } func (node *JSDocNonNullableType) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocNonNullableType(node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocNonNullableType(node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocNonNullableType(node *Node) bool { @@ -6991,32 +8003,36 @@ func IsJSDocNonNullableType(node *Node) bool { type JSDocNullableType struct { JSDocTypeBase - Type *TypeNode + typeNode link[Node] // *TypeNode } +func (node *JSDocNullableType) Type() *TypeNode { return node.typeNode.get() } + +func (node *JSDocNullableType) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + func (f *NodeFactory) NewJSDocNullableType(typeNode *TypeNode) *Node { - data := &JSDocNullableType{} - data.Type = typeNode + data := newData[JSDocNullableType](f) + data.typeNode.set(typeNode) return f.newNode(KindJSDocNullableType, data) } func (f *NodeFactory) UpdateJSDocNullableType(node *JSDocNullableType, typeNode *TypeNode) *Node { - if typeNode != node.Type { + if typeNode != node.Type() { return updateNode(f.NewJSDocNullableType(typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocNullableType) ForEachChild(v Visitor) bool { - return visit(v, node.Type) + return visit(v, node.Type()) } func (node *JSDocNullableType) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocNullableType(node, v.visitNode(node.Type)) + return v.Factory.UpdateJSDocNullableType(node, v.visitNode(node.Type())) } func (node *JSDocNullableType) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocNullableType(node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocNullableType(node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocNullableType(node *Node) bool { @@ -7032,7 +8048,7 @@ type JSDocAllType struct { } func (f *NodeFactory) NewJSDocAllType() *Node { - data := &JSDocAllType{} + data := newData[JSDocAllType](f) return f.newNode(KindJSDocAllType, data) } @@ -7050,32 +8066,36 @@ func IsJSDocAllType(node *Node) bool { type JSDocVariadicType struct { JSDocTypeBase - Type *TypeNode + typeNode link[Node] // *TypeNode } +func (node *JSDocVariadicType) Type() *TypeNode { return node.typeNode.get() } + +func (node *JSDocVariadicType) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + func (f *NodeFactory) NewJSDocVariadicType(typeNode *TypeNode) *Node { - data := &JSDocVariadicType{} - data.Type = typeNode + data := newData[JSDocVariadicType](f) + data.typeNode.set(typeNode) return f.newNode(KindJSDocVariadicType, data) } func (f *NodeFactory) UpdateJSDocVariadicType(node *JSDocVariadicType, typeNode *TypeNode) *Node { - if typeNode != node.Type { + if typeNode != node.Type() { return updateNode(f.NewJSDocVariadicType(typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocVariadicType) ForEachChild(v Visitor) bool { - return visit(v, node.Type) + return visit(v, node.Type()) } func (node *JSDocVariadicType) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocVariadicType(node, v.visitNode(node.Type)) + return v.Factory.UpdateJSDocVariadicType(node, v.visitNode(node.Type())) } func (node *JSDocVariadicType) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocVariadicType(node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocVariadicType(node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocVariadicType(node *Node) bool { @@ -7088,32 +8108,36 @@ func IsJSDocVariadicType(node *Node) bool { type JSDocOptionalType struct { JSDocTypeBase - Type *TypeNode + typeNode link[Node] // *TypeNode } +func (node *JSDocOptionalType) Type() *TypeNode { return node.typeNode.get() } + +func (node *JSDocOptionalType) SetType(typeNode *TypeNode) { node.typeNode.set(typeNode) } + func (f *NodeFactory) NewJSDocOptionalType(typeNode *TypeNode) *Node { - data := &JSDocOptionalType{} - data.Type = typeNode + data := newData[JSDocOptionalType](f) + data.typeNode.set(typeNode) return f.newNode(KindJSDocOptionalType, data) } func (f *NodeFactory) UpdateJSDocOptionalType(node *JSDocOptionalType, typeNode *TypeNode) *Node { - if typeNode != node.Type { + if typeNode != node.Type() { return updateNode(f.NewJSDocOptionalType(typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocOptionalType) ForEachChild(v Visitor) bool { - return visit(v, node.Type) + return visit(v, node.Type()) } func (node *JSDocOptionalType) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocOptionalType(node, v.visitNode(node.Type)) + return v.Factory.UpdateJSDocOptionalType(node, v.visitNode(node.Type())) } func (node *JSDocOptionalType) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocOptionalType(node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocOptionalType(node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocOptionalType(node *Node) bool { @@ -7126,34 +8150,40 @@ func IsJSDocOptionalType(node *Node) bool { type JSDocTypeTag struct { JSDocTagBase - TypeExpression *Node + typeExpression link[Node] // *Node +} + +func (node *JSDocTypeTag) TypeExpression() *Node { return node.typeExpression.get() } + +func (node *JSDocTypeTag) SetTypeExpression(typeExpression *Node) { + node.typeExpression.set(typeExpression) } func (f *NodeFactory) NewJSDocTypeTag(tagName *IdentifierNode, typeExpression *Node, comment *NodeList) *Node { - data := &JSDocTypeTag{} - data.TagName = tagName - data.TypeExpression = typeExpression - data.Comment = comment + data := newData[JSDocTypeTag](f) + data.tagName.set(tagName) + data.typeExpression.set(typeExpression) + data.comment.set(comment) return f.newNode(KindJSDocTypeTag, data) } func (f *NodeFactory) UpdateJSDocTypeTag(node *JSDocTypeTag, tagName *IdentifierNode, typeExpression *Node, comment *NodeList) *Node { - if tagName != node.TagName || typeExpression != node.TypeExpression || comment != node.Comment { + if tagName != node.TagName() || typeExpression != node.TypeExpression() || comment != node.Comment() { return updateNode(f.NewJSDocTypeTag(tagName, typeExpression, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocTypeTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || visit(v, node.TypeExpression) || visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || visit(v, node.TypeExpression()) || visitNodeList(v, node.Comment()) } func (node *JSDocTypeTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocTypeTag(node, v.visitNode(node.TagName), v.visitNode(node.TypeExpression), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocTypeTag(node, v.visitNode(node.TagName()), v.visitNode(node.TypeExpression()), v.visitNodes(node.Comment())) } func (node *JSDocTypeTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocTypeTag(node.TagName, node.TypeExpression, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocTypeTag(node.TagName(), node.TypeExpression(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocTypeTag(node *Node) bool { @@ -7169,29 +8199,29 @@ type JSDocUnknownTag struct { } func (f *NodeFactory) NewJSDocUnknownTag(tagName *IdentifierNode, comment *NodeList) *Node { - data := f.jsdocUnknownTagArena.New() - data.TagName = tagName - data.Comment = comment + data := newData[JSDocUnknownTag](f) + data.tagName.set(tagName) + data.comment.set(comment) return f.newNode(KindJSDocUnknownTag, data) } func (f *NodeFactory) UpdateJSDocUnknownTag(node *JSDocUnknownTag, tagName *IdentifierNode, comment *NodeList) *Node { - if tagName != node.TagName || comment != node.Comment { + if tagName != node.TagName() || comment != node.Comment() { return updateNode(f.NewJSDocUnknownTag(tagName, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocUnknownTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || visitNodeList(v, node.Comment()) } func (node *JSDocUnknownTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocUnknownTag(node, v.visitNode(node.TagName), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocUnknownTag(node, v.visitNode(node.TagName()), v.visitNodes(node.Comment())) } func (node *JSDocUnknownTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocUnknownTag(node.TagName, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocUnknownTag(node.TagName(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocUnknownTag(node *Node) bool { @@ -7204,39 +8234,49 @@ func IsJSDocUnknownTag(node *Node) bool { type JSDocTemplateTag struct { JSDocTagBase - Constraint *Node - TypeParameters *TypeParameterList + constraint link[Node] // *Node + typeParameters link[NodeList] // *TypeParameterList +} + +func (node *JSDocTemplateTag) Constraint() *Node { return node.constraint.get() } + +func (node *JSDocTemplateTag) SetConstraint(constraint *Node) { node.constraint.set(constraint) } + +func (node *JSDocTemplateTag) TypeParameters() *TypeParameterList { return node.typeParameters.get() } + +func (node *JSDocTemplateTag) SetTypeParameters(typeParameters *TypeParameterList) { + node.typeParameters.set(typeParameters) } func (f *NodeFactory) NewJSDocTemplateTag(tagName *IdentifierNode, constraint *Node, typeParameters *TypeParameterList, comment *NodeList) *Node { - data := &JSDocTemplateTag{} - data.TagName = tagName - data.Constraint = constraint - data.TypeParameters = typeParameters - data.Comment = comment + data := newData[JSDocTemplateTag](f) + data.tagName.set(tagName) + data.constraint.set(constraint) + data.typeParameters.set(typeParameters) + data.comment.set(comment) return f.newNode(KindJSDocTemplateTag, data) } func (f *NodeFactory) UpdateJSDocTemplateTag(node *JSDocTemplateTag, tagName *IdentifierNode, constraint *Node, typeParameters *TypeParameterList, comment *NodeList) *Node { - if tagName != node.TagName || constraint != node.Constraint || typeParameters != node.TypeParameters || comment != node.Comment { + if tagName != node.TagName() || constraint != node.Constraint() || typeParameters != node.TypeParameters() || comment != node.Comment() { return updateNode(f.NewJSDocTemplateTag(tagName, constraint, typeParameters, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocTemplateTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || - visit(v, node.Constraint) || - visitNodeList(v, node.TypeParameters) || - visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || + visit(v, node.Constraint()) || + visitNodeList(v, node.TypeParameters()) || + visitNodeList(v, node.Comment()) } func (node *JSDocTemplateTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocTemplateTag(node, v.visitNode(node.TagName), v.visitNode(node.Constraint), v.visitNodes(node.TypeParameters), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocTemplateTag(node, v.visitNode(node.TagName()), v.visitNode(node.Constraint()), v.visitNodes(node.TypeParameters()), v.visitNodes(node.Comment())) } func (node *JSDocTemplateTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocTemplateTag(node.TagName, node.Constraint, node.TypeParameters, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocTemplateTag(node.TagName(), node.Constraint(), node.TypeParameters(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocTemplateTag(node *Node) bool { @@ -7249,34 +8289,40 @@ func IsJSDocTemplateTag(node *Node) bool { type JSDocReturnTag struct { JSDocTagBase - TypeExpression *TypeNode // Optional + typeExpression link[Node] // *TypeNode. Optional +} + +func (node *JSDocReturnTag) TypeExpression() *TypeNode { return node.typeExpression.get() } + +func (node *JSDocReturnTag) SetTypeExpression(typeExpression *TypeNode) { + node.typeExpression.set(typeExpression) } func (f *NodeFactory) NewJSDocReturnTag(tagName *IdentifierNode, typeExpression *TypeNode, comment *NodeList) *Node { - data := &JSDocReturnTag{} - data.TagName = tagName - data.TypeExpression = typeExpression - data.Comment = comment + data := newData[JSDocReturnTag](f) + data.tagName.set(tagName) + data.typeExpression.set(typeExpression) + data.comment.set(comment) return f.newNode(KindJSDocReturnTag, data) } func (f *NodeFactory) UpdateJSDocReturnTag(node *JSDocReturnTag, tagName *IdentifierNode, typeExpression *TypeNode, comment *NodeList) *Node { - if tagName != node.TagName || typeExpression != node.TypeExpression || comment != node.Comment { + if tagName != node.TagName() || typeExpression != node.TypeExpression() || comment != node.Comment() { return updateNode(f.NewJSDocReturnTag(tagName, typeExpression, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocReturnTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || visit(v, node.TypeExpression) || visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || visit(v, node.TypeExpression()) || visitNodeList(v, node.Comment()) } func (node *JSDocReturnTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocReturnTag(node, v.visitNode(node.TagName), v.visitNode(node.TypeExpression), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocReturnTag(node, v.visitNode(node.TagName()), v.visitNode(node.TypeExpression()), v.visitNodes(node.Comment())) } func (node *JSDocReturnTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocReturnTag(node.TagName, node.TypeExpression, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocReturnTag(node.TagName(), node.TypeExpression(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocReturnTag(node *Node) bool { @@ -7292,29 +8338,29 @@ type JSDocPublicTag struct { } func (f *NodeFactory) NewJSDocPublicTag(tagName *IdentifierNode, comment *NodeList) *Node { - data := &JSDocPublicTag{} - data.TagName = tagName - data.Comment = comment + data := newData[JSDocPublicTag](f) + data.tagName.set(tagName) + data.comment.set(comment) return f.newNode(KindJSDocPublicTag, data) } func (f *NodeFactory) UpdateJSDocPublicTag(node *JSDocPublicTag, tagName *IdentifierNode, comment *NodeList) *Node { - if tagName != node.TagName || comment != node.Comment { + if tagName != node.TagName() || comment != node.Comment() { return updateNode(f.NewJSDocPublicTag(tagName, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocPublicTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || visitNodeList(v, node.Comment()) } func (node *JSDocPublicTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocPublicTag(node, v.visitNode(node.TagName), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocPublicTag(node, v.visitNode(node.TagName()), v.visitNodes(node.Comment())) } func (node *JSDocPublicTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocPublicTag(node.TagName, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocPublicTag(node.TagName(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocPublicTag(node *Node) bool { @@ -7330,29 +8376,29 @@ type JSDocPrivateTag struct { } func (f *NodeFactory) NewJSDocPrivateTag(tagName *IdentifierNode, comment *NodeList) *Node { - data := &JSDocPrivateTag{} - data.TagName = tagName - data.Comment = comment + data := newData[JSDocPrivateTag](f) + data.tagName.set(tagName) + data.comment.set(comment) return f.newNode(KindJSDocPrivateTag, data) } func (f *NodeFactory) UpdateJSDocPrivateTag(node *JSDocPrivateTag, tagName *IdentifierNode, comment *NodeList) *Node { - if tagName != node.TagName || comment != node.Comment { + if tagName != node.TagName() || comment != node.Comment() { return updateNode(f.NewJSDocPrivateTag(tagName, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocPrivateTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || visitNodeList(v, node.Comment()) } func (node *JSDocPrivateTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocPrivateTag(node, v.visitNode(node.TagName), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocPrivateTag(node, v.visitNode(node.TagName()), v.visitNodes(node.Comment())) } func (node *JSDocPrivateTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocPrivateTag(node.TagName, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocPrivateTag(node.TagName(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocPrivateTag(node *Node) bool { @@ -7368,29 +8414,29 @@ type JSDocProtectedTag struct { } func (f *NodeFactory) NewJSDocProtectedTag(tagName *IdentifierNode, comment *NodeList) *Node { - data := &JSDocProtectedTag{} - data.TagName = tagName - data.Comment = comment + data := newData[JSDocProtectedTag](f) + data.tagName.set(tagName) + data.comment.set(comment) return f.newNode(KindJSDocProtectedTag, data) } func (f *NodeFactory) UpdateJSDocProtectedTag(node *JSDocProtectedTag, tagName *IdentifierNode, comment *NodeList) *Node { - if tagName != node.TagName || comment != node.Comment { + if tagName != node.TagName() || comment != node.Comment() { return updateNode(f.NewJSDocProtectedTag(tagName, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocProtectedTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || visitNodeList(v, node.Comment()) } func (node *JSDocProtectedTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocProtectedTag(node, v.visitNode(node.TagName), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocProtectedTag(node, v.visitNode(node.TagName()), v.visitNodes(node.Comment())) } func (node *JSDocProtectedTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocProtectedTag(node.TagName, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocProtectedTag(node.TagName(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocProtectedTag(node *Node) bool { @@ -7406,29 +8452,29 @@ type JSDocReadonlyTag struct { } func (f *NodeFactory) NewJSDocReadonlyTag(tagName *IdentifierNode, comment *NodeList) *Node { - data := &JSDocReadonlyTag{} - data.TagName = tagName - data.Comment = comment + data := newData[JSDocReadonlyTag](f) + data.tagName.set(tagName) + data.comment.set(comment) return f.newNode(KindJSDocReadonlyTag, data) } func (f *NodeFactory) UpdateJSDocReadonlyTag(node *JSDocReadonlyTag, tagName *IdentifierNode, comment *NodeList) *Node { - if tagName != node.TagName || comment != node.Comment { + if tagName != node.TagName() || comment != node.Comment() { return updateNode(f.NewJSDocReadonlyTag(tagName, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocReadonlyTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || visitNodeList(v, node.Comment()) } func (node *JSDocReadonlyTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocReadonlyTag(node, v.visitNode(node.TagName), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocReadonlyTag(node, v.visitNode(node.TagName()), v.visitNodes(node.Comment())) } func (node *JSDocReadonlyTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocReadonlyTag(node.TagName, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocReadonlyTag(node.TagName(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocReadonlyTag(node *Node) bool { @@ -7444,29 +8490,29 @@ type JSDocOverrideTag struct { } func (f *NodeFactory) NewJSDocOverrideTag(tagName *IdentifierNode, comment *NodeList) *Node { - data := &JSDocOverrideTag{} - data.TagName = tagName - data.Comment = comment + data := newData[JSDocOverrideTag](f) + data.tagName.set(tagName) + data.comment.set(comment) return f.newNode(KindJSDocOverrideTag, data) } func (f *NodeFactory) UpdateJSDocOverrideTag(node *JSDocOverrideTag, tagName *IdentifierNode, comment *NodeList) *Node { - if tagName != node.TagName || comment != node.Comment { + if tagName != node.TagName() || comment != node.Comment() { return updateNode(f.NewJSDocOverrideTag(tagName, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocOverrideTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || visitNodeList(v, node.Comment()) } func (node *JSDocOverrideTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocOverrideTag(node, v.visitNode(node.TagName), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocOverrideTag(node, v.visitNode(node.TagName()), v.visitNodes(node.Comment())) } func (node *JSDocOverrideTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocOverrideTag(node.TagName, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocOverrideTag(node.TagName(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocOverrideTag(node *Node) bool { @@ -7482,29 +8528,29 @@ type JSDocDeprecatedTag struct { } func (f *NodeFactory) NewJSDocDeprecatedTag(tagName *IdentifierNode, comment *NodeList) *Node { - data := f.jsdocDeprecatedTagArena.New() - data.TagName = tagName - data.Comment = comment + data := newData[JSDocDeprecatedTag](f) + data.tagName.set(tagName) + data.comment.set(comment) return f.newNode(KindJSDocDeprecatedTag, data) } func (f *NodeFactory) UpdateJSDocDeprecatedTag(node *JSDocDeprecatedTag, tagName *IdentifierNode, comment *NodeList) *Node { - if tagName != node.TagName || comment != node.Comment { + if tagName != node.TagName() || comment != node.Comment() { return updateNode(f.NewJSDocDeprecatedTag(tagName, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocDeprecatedTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || visitNodeList(v, node.Comment()) } func (node *JSDocDeprecatedTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocDeprecatedTag(node, v.visitNode(node.TagName), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocDeprecatedTag(node, v.visitNode(node.TagName()), v.visitNodes(node.Comment())) } func (node *JSDocDeprecatedTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocDeprecatedTag(node.TagName, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocDeprecatedTag(node.TagName(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocDeprecatedTag(node *Node) bool { @@ -7517,34 +8563,40 @@ func IsJSDocDeprecatedTag(node *Node) bool { type JSDocSeeTag struct { JSDocTagBase - NameExpression *TypeNode + nameExpression link[Node] // *TypeNode +} + +func (node *JSDocSeeTag) NameExpression() *TypeNode { return node.nameExpression.get() } + +func (node *JSDocSeeTag) SetNameExpression(nameExpression *TypeNode) { + node.nameExpression.set(nameExpression) } func (f *NodeFactory) NewJSDocSeeTag(tagName *IdentifierNode, nameExpression *TypeNode, comment *NodeList) *Node { - data := &JSDocSeeTag{} - data.TagName = tagName - data.NameExpression = nameExpression - data.Comment = comment + data := newData[JSDocSeeTag](f) + data.tagName.set(tagName) + data.nameExpression.set(nameExpression) + data.comment.set(comment) return f.newNode(KindJSDocSeeTag, data) } func (f *NodeFactory) UpdateJSDocSeeTag(node *JSDocSeeTag, tagName *IdentifierNode, nameExpression *TypeNode, comment *NodeList) *Node { - if tagName != node.TagName || nameExpression != node.NameExpression || comment != node.Comment { + if tagName != node.TagName() || nameExpression != node.NameExpression() || comment != node.Comment() { return updateNode(f.NewJSDocSeeTag(tagName, nameExpression, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocSeeTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || visit(v, node.NameExpression) || visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || visit(v, node.NameExpression()) || visitNodeList(v, node.Comment()) } func (node *JSDocSeeTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocSeeTag(node, v.visitNode(node.TagName), v.visitNode(node.NameExpression), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocSeeTag(node, v.visitNode(node.TagName()), v.visitNode(node.NameExpression()), v.visitNodes(node.Comment())) } func (node *JSDocSeeTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocSeeTag(node.TagName, node.NameExpression, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocSeeTag(node.TagName(), node.NameExpression(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocSeeTag(node *Node) bool { @@ -7557,34 +8609,42 @@ func IsJSDocSeeTag(node *Node) bool { type JSDocImplementsTag struct { JSDocTagBase - ClassName *ExpressionWithTypeArgumentsNode + className link[Node] // *ExpressionWithTypeArgumentsNode +} + +func (node *JSDocImplementsTag) ClassName() *ExpressionWithTypeArgumentsNode { + return node.className.get() +} + +func (node *JSDocImplementsTag) SetClassName(className *ExpressionWithTypeArgumentsNode) { + node.className.set(className) } func (f *NodeFactory) NewJSDocImplementsTag(tagName *IdentifierNode, className *ExpressionWithTypeArgumentsNode, comment *NodeList) *Node { - data := &JSDocImplementsTag{} - data.TagName = tagName - data.ClassName = className - data.Comment = comment + data := newData[JSDocImplementsTag](f) + data.tagName.set(tagName) + data.className.set(className) + data.comment.set(comment) return f.newNode(KindJSDocImplementsTag, data) } func (f *NodeFactory) UpdateJSDocImplementsTag(node *JSDocImplementsTag, tagName *IdentifierNode, className *ExpressionWithTypeArgumentsNode, comment *NodeList) *Node { - if tagName != node.TagName || className != node.ClassName || comment != node.Comment { + if tagName != node.TagName() || className != node.ClassName() || comment != node.Comment() { return updateNode(f.NewJSDocImplementsTag(tagName, className, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocImplementsTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || visit(v, node.ClassName) || visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || visit(v, node.ClassName()) || visitNodeList(v, node.Comment()) } func (node *JSDocImplementsTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocImplementsTag(node, v.visitNode(node.TagName), v.visitNode(node.ClassName), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocImplementsTag(node, v.visitNode(node.TagName()), v.visitNode(node.ClassName()), v.visitNodes(node.Comment())) } func (node *JSDocImplementsTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocImplementsTag(node.TagName, node.ClassName, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocImplementsTag(node.TagName(), node.ClassName(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocImplementsTag(node *Node) bool { @@ -7597,34 +8657,42 @@ func IsJSDocImplementsTag(node *Node) bool { type JSDocAugmentsTag struct { JSDocTagBase - ClassName *ExpressionWithTypeArgumentsNode + className link[Node] // *ExpressionWithTypeArgumentsNode +} + +func (node *JSDocAugmentsTag) ClassName() *ExpressionWithTypeArgumentsNode { + return node.className.get() +} + +func (node *JSDocAugmentsTag) SetClassName(className *ExpressionWithTypeArgumentsNode) { + node.className.set(className) } func (f *NodeFactory) NewJSDocAugmentsTag(tagName *IdentifierNode, className *ExpressionWithTypeArgumentsNode, comment *NodeList) *Node { - data := &JSDocAugmentsTag{} - data.TagName = tagName - data.ClassName = className - data.Comment = comment + data := newData[JSDocAugmentsTag](f) + data.tagName.set(tagName) + data.className.set(className) + data.comment.set(comment) return f.newNode(KindJSDocAugmentsTag, data) } func (f *NodeFactory) UpdateJSDocAugmentsTag(node *JSDocAugmentsTag, tagName *IdentifierNode, className *ExpressionWithTypeArgumentsNode, comment *NodeList) *Node { - if tagName != node.TagName || className != node.ClassName || comment != node.Comment { + if tagName != node.TagName() || className != node.ClassName() || comment != node.Comment() { return updateNode(f.NewJSDocAugmentsTag(tagName, className, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocAugmentsTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || visit(v, node.ClassName) || visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || visit(v, node.ClassName()) || visitNodeList(v, node.Comment()) } func (node *JSDocAugmentsTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocAugmentsTag(node, v.visitNode(node.TagName), v.visitNode(node.ClassName), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocAugmentsTag(node, v.visitNode(node.TagName()), v.visitNode(node.ClassName()), v.visitNodes(node.Comment())) } func (node *JSDocAugmentsTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocAugmentsTag(node.TagName, node.ClassName, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocAugmentsTag(node.TagName(), node.ClassName(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocAugmentsTag(node *Node) bool { @@ -7637,34 +8705,40 @@ func IsJSDocAugmentsTag(node *Node) bool { type JSDocSatisfiesTag struct { JSDocTagBase - TypeExpression *TypeNode + typeExpression link[Node] // *TypeNode +} + +func (node *JSDocSatisfiesTag) TypeExpression() *TypeNode { return node.typeExpression.get() } + +func (node *JSDocSatisfiesTag) SetTypeExpression(typeExpression *TypeNode) { + node.typeExpression.set(typeExpression) } func (f *NodeFactory) NewJSDocSatisfiesTag(tagName *IdentifierNode, typeExpression *TypeNode, comment *NodeList) *Node { - data := &JSDocSatisfiesTag{} - data.TagName = tagName - data.TypeExpression = typeExpression - data.Comment = comment + data := newData[JSDocSatisfiesTag](f) + data.tagName.set(tagName) + data.typeExpression.set(typeExpression) + data.comment.set(comment) return f.newNode(KindJSDocSatisfiesTag, data) } func (f *NodeFactory) UpdateJSDocSatisfiesTag(node *JSDocSatisfiesTag, tagName *IdentifierNode, typeExpression *TypeNode, comment *NodeList) *Node { - if tagName != node.TagName || typeExpression != node.TypeExpression || comment != node.Comment { + if tagName != node.TagName() || typeExpression != node.TypeExpression() || comment != node.Comment() { return updateNode(f.NewJSDocSatisfiesTag(tagName, typeExpression, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocSatisfiesTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || visit(v, node.TypeExpression) || visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || visit(v, node.TypeExpression()) || visitNodeList(v, node.Comment()) } func (node *JSDocSatisfiesTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocSatisfiesTag(node, v.visitNode(node.TagName), v.visitNode(node.TypeExpression), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocSatisfiesTag(node, v.visitNode(node.TagName()), v.visitNode(node.TypeExpression()), v.visitNodes(node.Comment())) } func (node *JSDocSatisfiesTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocSatisfiesTag(node.TagName, node.TypeExpression, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocSatisfiesTag(node.TagName(), node.TypeExpression(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocSatisfiesTag(node *Node) bool { @@ -7677,34 +8751,40 @@ func IsJSDocSatisfiesTag(node *Node) bool { type JSDocThrowsTag struct { JSDocTagBase - TypeExpression *TypeNode // Optional + typeExpression link[Node] // *TypeNode. Optional +} + +func (node *JSDocThrowsTag) TypeExpression() *TypeNode { return node.typeExpression.get() } + +func (node *JSDocThrowsTag) SetTypeExpression(typeExpression *TypeNode) { + node.typeExpression.set(typeExpression) } func (f *NodeFactory) NewJSDocThrowsTag(tagName *IdentifierNode, typeExpression *TypeNode, comment *NodeList) *Node { - data := &JSDocThrowsTag{} - data.TagName = tagName - data.TypeExpression = typeExpression - data.Comment = comment + data := newData[JSDocThrowsTag](f) + data.tagName.set(tagName) + data.typeExpression.set(typeExpression) + data.comment.set(comment) return f.newNode(KindJSDocThrowsTag, data) } func (f *NodeFactory) UpdateJSDocThrowsTag(node *JSDocThrowsTag, tagName *IdentifierNode, typeExpression *TypeNode, comment *NodeList) *Node { - if tagName != node.TagName || typeExpression != node.TypeExpression || comment != node.Comment { + if tagName != node.TagName() || typeExpression != node.TypeExpression() || comment != node.Comment() { return updateNode(f.NewJSDocThrowsTag(tagName, typeExpression, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocThrowsTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || visit(v, node.TypeExpression) || visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || visit(v, node.TypeExpression()) || visitNodeList(v, node.Comment()) } func (node *JSDocThrowsTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocThrowsTag(node, v.visitNode(node.TagName), v.visitNode(node.TypeExpression), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocThrowsTag(node, v.visitNode(node.TagName()), v.visitNode(node.TypeExpression()), v.visitNodes(node.Comment())) } func (node *JSDocThrowsTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocThrowsTag(node.TagName, node.TypeExpression, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocThrowsTag(node.TagName(), node.TypeExpression(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocThrowsTag(node *Node) bool { @@ -7717,34 +8797,40 @@ func IsJSDocThrowsTag(node *Node) bool { type JSDocThisTag struct { JSDocTagBase - TypeExpression *TypeNode + typeExpression link[Node] // *TypeNode +} + +func (node *JSDocThisTag) TypeExpression() *TypeNode { return node.typeExpression.get() } + +func (node *JSDocThisTag) SetTypeExpression(typeExpression *TypeNode) { + node.typeExpression.set(typeExpression) } func (f *NodeFactory) NewJSDocThisTag(tagName *IdentifierNode, typeExpression *TypeNode, comment *NodeList) *Node { - data := &JSDocThisTag{} - data.TagName = tagName - data.TypeExpression = typeExpression - data.Comment = comment + data := newData[JSDocThisTag](f) + data.tagName.set(tagName) + data.typeExpression.set(typeExpression) + data.comment.set(comment) return f.newNode(KindJSDocThisTag, data) } func (f *NodeFactory) UpdateJSDocThisTag(node *JSDocThisTag, tagName *IdentifierNode, typeExpression *TypeNode, comment *NodeList) *Node { - if tagName != node.TagName || typeExpression != node.TypeExpression || comment != node.Comment { + if tagName != node.TagName() || typeExpression != node.TypeExpression() || comment != node.Comment() { return updateNode(f.NewJSDocThisTag(tagName, typeExpression, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocThisTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || visit(v, node.TypeExpression) || visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || visit(v, node.TypeExpression()) || visitNodeList(v, node.Comment()) } func (node *JSDocThisTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocThisTag(node, v.visitNode(node.TagName), v.visitNode(node.TypeExpression), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocThisTag(node, v.visitNode(node.TagName()), v.visitNode(node.TypeExpression()), v.visitNodes(node.Comment())) } func (node *JSDocThisTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocThisTag(node.TagName, node.TypeExpression, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocThisTag(node.TagName(), node.TypeExpression(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocThisTag(node *Node) bool { @@ -7757,42 +8843,60 @@ func IsJSDocThisTag(node *Node) bool { type JSDocImportTag struct { JSDocTagBase - ImportClause *ImportClauseNode // Optional - ModuleSpecifier *Expression - Attributes *ImportAttributesNode // Optional + importClause link[Node] // *ImportClauseNode. Optional + moduleSpecifier link[Node] // *Expression + attributes link[Node] // *ImportAttributesNode. Optional +} + +func (node *JSDocImportTag) ImportClause() *ImportClauseNode { return node.importClause.get() } + +func (node *JSDocImportTag) SetImportClause(importClause *ImportClauseNode) { + node.importClause.set(importClause) +} + +func (node *JSDocImportTag) ModuleSpecifier() *Expression { return node.moduleSpecifier.get() } + +func (node *JSDocImportTag) SetModuleSpecifier(moduleSpecifier *Expression) { + node.moduleSpecifier.set(moduleSpecifier) +} + +func (node *JSDocImportTag) Attributes() *ImportAttributesNode { return node.attributes.get() } + +func (node *JSDocImportTag) SetAttributes(attributes *ImportAttributesNode) { + node.attributes.set(attributes) } func (f *NodeFactory) NewJSDocImportTag(tagName *IdentifierNode, importClause *ImportClauseNode, moduleSpecifier *Expression, attributes *ImportAttributesNode, comment *NodeList) *Node { - data := &JSDocImportTag{} - data.TagName = tagName - data.ImportClause = importClause - data.ModuleSpecifier = moduleSpecifier - data.Attributes = attributes - data.Comment = comment + data := newData[JSDocImportTag](f) + data.tagName.set(tagName) + data.importClause.set(importClause) + data.moduleSpecifier.set(moduleSpecifier) + data.attributes.set(attributes) + data.comment.set(comment) return f.newNode(KindJSDocImportTag, data) } func (f *NodeFactory) UpdateJSDocImportTag(node *JSDocImportTag, tagName *IdentifierNode, importClause *ImportClauseNode, moduleSpecifier *Expression, attributes *ImportAttributesNode, comment *NodeList) *Node { - if tagName != node.TagName || importClause != node.ImportClause || moduleSpecifier != node.ModuleSpecifier || attributes != node.Attributes || comment != node.Comment { + if tagName != node.TagName() || importClause != node.ImportClause() || moduleSpecifier != node.ModuleSpecifier() || attributes != node.Attributes() || comment != node.Comment() { return updateNode(f.NewJSDocImportTag(tagName, importClause, moduleSpecifier, attributes, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocImportTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || - visit(v, node.ImportClause) || - visit(v, node.ModuleSpecifier) || - visit(v, node.Attributes) || - visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || + visit(v, node.ImportClause()) || + visit(v, node.ModuleSpecifier()) || + visit(v, node.Attributes()) || + visitNodeList(v, node.Comment()) } func (node *JSDocImportTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocImportTag(node, v.visitNode(node.TagName), v.visitNode(node.ImportClause), v.visitNode(node.ModuleSpecifier), v.visitNode(node.Attributes), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocImportTag(node, v.visitNode(node.TagName()), v.visitNode(node.ImportClause()), v.visitNode(node.ModuleSpecifier()), v.visitNode(node.Attributes()), v.visitNodes(node.Comment())) } func (node *JSDocImportTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocImportTag(node.TagName, node.ImportClause, node.ModuleSpecifier, node.Attributes, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocImportTag(node.TagName(), node.ImportClause(), node.ModuleSpecifier(), node.Attributes(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocImportTag(node *Node) bool { @@ -7805,43 +8909,49 @@ func IsJSDocImportTag(node *Node) bool { type JSDocCallbackTag struct { JSDocTagBase - TypeExpression *TypeNode - name *JSDocFullName // Optional + typeExpression link[Node] // *TypeNode + name link[Node] // *JSDocFullName. Optional +} + +func (node *JSDocCallbackTag) TypeExpression() *TypeNode { return node.typeExpression.get() } + +func (node *JSDocCallbackTag) SetTypeExpression(typeExpression *TypeNode) { + node.typeExpression.set(typeExpression) } func (f *NodeFactory) NewJSDocCallbackTag(tagName *IdentifierNode, typeExpression *TypeNode, name *JSDocFullName, comment *NodeList) *Node { - data := &JSDocCallbackTag{} - data.TagName = tagName - data.TypeExpression = typeExpression - data.name = name - data.Comment = comment + data := newData[JSDocCallbackTag](f) + data.tagName.set(tagName) + data.typeExpression.set(typeExpression) + data.name.set(name) + data.comment.set(comment) return f.newNode(KindJSDocCallbackTag, data) } func (f *NodeFactory) UpdateJSDocCallbackTag(node *JSDocCallbackTag, tagName *IdentifierNode, typeExpression *TypeNode, name *JSDocFullName, comment *NodeList) *Node { - if tagName != node.TagName || typeExpression != node.TypeExpression || name != node.name || comment != node.Comment { + if tagName != node.TagName() || typeExpression != node.TypeExpression() || name != node.name.get() || comment != node.Comment() { return updateNode(f.NewJSDocCallbackTag(tagName, typeExpression, name, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocCallbackTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || - visit(v, node.TypeExpression) || - visit(v, node.name) || - visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || + visit(v, node.TypeExpression()) || + visit(v, node.name.get()) || + visitNodeList(v, node.Comment()) } func (node *JSDocCallbackTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocCallbackTag(node, v.visitNode(node.TagName), v.visitNode(node.TypeExpression), v.visitNode(node.name), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocCallbackTag(node, v.visitNode(node.TagName()), v.visitNode(node.TypeExpression()), v.visitNode(node.name.get()), v.visitNodes(node.Comment())) } func (node *JSDocCallbackTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocCallbackTag(node.TagName, node.TypeExpression, node.name, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocCallbackTag(node.TagName(), node.TypeExpression(), node.name.get(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *JSDocCallbackTag) Name() *DeclarationName { - return node.name + return node.name.get() } func IsJSDocCallbackTag(node *Node) bool { @@ -7854,34 +8964,40 @@ func IsJSDocCallbackTag(node *Node) bool { type JSDocOverloadTag struct { JSDocTagBase - TypeExpression *TypeNode + typeExpression link[Node] // *TypeNode +} + +func (node *JSDocOverloadTag) TypeExpression() *TypeNode { return node.typeExpression.get() } + +func (node *JSDocOverloadTag) SetTypeExpression(typeExpression *TypeNode) { + node.typeExpression.set(typeExpression) } func (f *NodeFactory) NewJSDocOverloadTag(tagName *IdentifierNode, typeExpression *TypeNode, comment *NodeList) *Node { - data := &JSDocOverloadTag{} - data.TagName = tagName - data.TypeExpression = typeExpression - data.Comment = comment + data := newData[JSDocOverloadTag](f) + data.tagName.set(tagName) + data.typeExpression.set(typeExpression) + data.comment.set(comment) return f.newNode(KindJSDocOverloadTag, data) } func (f *NodeFactory) UpdateJSDocOverloadTag(node *JSDocOverloadTag, tagName *IdentifierNode, typeExpression *TypeNode, comment *NodeList) *Node { - if tagName != node.TagName || typeExpression != node.TypeExpression || comment != node.Comment { + if tagName != node.TagName() || typeExpression != node.TypeExpression() || comment != node.Comment() { return updateNode(f.NewJSDocOverloadTag(tagName, typeExpression, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocOverloadTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || visit(v, node.TypeExpression) || visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || visit(v, node.TypeExpression()) || visitNodeList(v, node.Comment()) } func (node *JSDocOverloadTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocOverloadTag(node, v.visitNode(node.TagName), v.visitNode(node.TypeExpression), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocOverloadTag(node, v.visitNode(node.TagName()), v.visitNode(node.TypeExpression()), v.visitNodes(node.Comment())) } func (node *JSDocOverloadTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocOverloadTag(node.TagName, node.TypeExpression, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocOverloadTag(node.TagName(), node.TypeExpression(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocOverloadTag(node *Node) bool { @@ -7894,43 +9010,49 @@ func IsJSDocOverloadTag(node *Node) bool { type JSDocTypedefTag struct { JSDocTagBase - TypeExpression *Node // Optional - name *JSDocFullName // Optional + typeExpression link[Node] // *Node. Optional + name link[Node] // *JSDocFullName. Optional +} + +func (node *JSDocTypedefTag) TypeExpression() *Node { return node.typeExpression.get() } + +func (node *JSDocTypedefTag) SetTypeExpression(typeExpression *Node) { + node.typeExpression.set(typeExpression) } func (f *NodeFactory) NewJSDocTypedefTag(tagName *IdentifierNode, typeExpression *Node, name *JSDocFullName, comment *NodeList) *Node { - data := &JSDocTypedefTag{} - data.TagName = tagName - data.TypeExpression = typeExpression - data.name = name - data.Comment = comment + data := newData[JSDocTypedefTag](f) + data.tagName.set(tagName) + data.typeExpression.set(typeExpression) + data.name.set(name) + data.comment.set(comment) return f.newNode(KindJSDocTypedefTag, data) } func (f *NodeFactory) UpdateJSDocTypedefTag(node *JSDocTypedefTag, tagName *IdentifierNode, typeExpression *Node, name *JSDocFullName, comment *NodeList) *Node { - if tagName != node.TagName || typeExpression != node.TypeExpression || name != node.name || comment != node.Comment { + if tagName != node.TagName() || typeExpression != node.TypeExpression() || name != node.name.get() || comment != node.Comment() { return updateNode(f.NewJSDocTypedefTag(tagName, typeExpression, name, comment), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocTypedefTag) ForEachChild(v Visitor) bool { - return visit(v, node.TagName) || - visit(v, node.TypeExpression) || - visit(v, node.name) || - visitNodeList(v, node.Comment) + return visit(v, node.TagName()) || + visit(v, node.TypeExpression()) || + visit(v, node.name.get()) || + visitNodeList(v, node.Comment()) } func (node *JSDocTypedefTag) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocTypedefTag(node, v.visitNode(node.TagName), v.visitNode(node.TypeExpression), v.visitNode(node.name), v.visitNodes(node.Comment)) + return v.Factory.UpdateJSDocTypedefTag(node, v.visitNode(node.TagName()), v.visitNode(node.TypeExpression()), v.visitNode(node.name.get()), v.visitNodes(node.Comment())) } func (node *JSDocTypedefTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocTypedefTag(node.TagName, node.TypeExpression, node.name, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocTypedefTag(node.TagName(), node.TypeExpression(), node.name.get(), node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *JSDocTypedefTag) Name() *DeclarationName { - return node.name + return node.name.get() } func IsJSDocTypedefTag(node *Node) bool { @@ -7948,30 +9070,30 @@ type JSDocSignature struct { } func (f *NodeFactory) NewJSDocSignature(typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode) *Node { - data := &JSDocSignature{} - data.TypeParameters = typeParameters - data.Parameters = parameters - data.Type = typeNode + data := newData[JSDocSignature](f) + data.typeParameters.set(typeParameters) + data.parameters.set(parameters) + data.typeNode.set(typeNode) return f.newNode(KindJSDocSignature, data) } func (f *NodeFactory) UpdateJSDocSignature(node *JSDocSignature, typeParameters *TypeParameterList, parameters *ParameterList, typeNode *TypeNode) *Node { - if typeParameters != node.TypeParameters || parameters != node.Parameters || typeNode != node.Type { + if typeParameters != node.TypeParameters() || parameters != node.Parameters() || typeNode != node.Type() { return updateNode(f.NewJSDocSignature(typeParameters, parameters, typeNode), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocSignature) ForEachChild(v Visitor) bool { - return visitNodeList(v, node.TypeParameters) || visitNodeList(v, node.Parameters) || visit(v, node.Type) + return visitNodeList(v, node.TypeParameters()) || visitNodeList(v, node.Parameters()) || visit(v, node.Type()) } func (node *JSDocSignature) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocSignature(node, v.visitNodes(node.TypeParameters), v.visitNodes(node.Parameters), v.visitNode(node.Type)) + return v.Factory.UpdateJSDocSignature(node, v.visitNodes(node.TypeParameters()), v.visitNodes(node.Parameters()), v.visitNode(node.Type())) } func (node *JSDocSignature) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocSignature(node.TypeParameters, node.Parameters, node.Type), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocSignature(node.TypeParameters(), node.Parameters(), node.Type()), node.AsNode(), f.AsNodeFactory().hooks) } func IsJSDocSignature(node *Node) bool { @@ -7984,36 +9106,36 @@ func IsJSDocSignature(node *Node) bool { type JSDocNameReference struct { TypeNodeBase - name *EntityName + name link[Node] // *EntityName } func (f *NodeFactory) NewJSDocNameReference(name *EntityName) *Node { - data := &JSDocNameReference{} - data.name = name + data := newData[JSDocNameReference](f) + data.name.set(name) return f.newNode(KindJSDocNameReference, data) } func (f *NodeFactory) UpdateJSDocNameReference(node *JSDocNameReference, name *EntityName) *Node { - if name != node.name { + if name != node.name.get() { return updateNode(f.NewJSDocNameReference(name), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocNameReference) ForEachChild(v Visitor) bool { - return visit(v, node.name) + return visit(v, node.name.get()) } func (node *JSDocNameReference) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocNameReference(node, v.visitNode(node.name)) + return v.Factory.UpdateJSDocNameReference(node, v.visitNode(node.name.get())) } func (node *JSDocNameReference) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocNameReference(node.name), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocNameReference(node.name.get()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *JSDocNameReference) Name() *DeclarationName { - return node.name + return node.name.get() } func IsJSDocNameReference(node *Node) bool { @@ -8042,44 +9164,50 @@ type ModuleDeclaration struct { BodyBase CompositeBase Keyword Kind - name *ModuleName - Attributes *TypeLiteralNodeNode // Optional + name link[Node] // *ModuleName + attributes link[Node] // *TypeLiteralNodeNode. Optional +} + +func (node *ModuleDeclaration) Attributes() *TypeLiteralNodeNode { return node.attributes.get() } + +func (node *ModuleDeclaration) SetAttributes(attributes *TypeLiteralNodeNode) { + node.attributes.set(attributes) } func (f *NodeFactory) NewModuleDeclaration(modifiers *ModifierList, keyword Kind, name *ModuleName, attributes *TypeLiteralNodeNode, body *ModuleBody) *Node { - data := &ModuleDeclaration{} - data.modifiers = modifiers + data := newData[ModuleDeclaration](f) + data.modifiers.set(modifiers) data.Keyword = keyword - data.name = name - data.Attributes = attributes - data.Body = body + data.name.set(name) + data.attributes.set(attributes) + data.body.set(body) return f.newNode(KindModuleDeclaration, data) } func (f *NodeFactory) UpdateModuleDeclaration(node *ModuleDeclaration, modifiers *ModifierList, keyword Kind, name *ModuleName, attributes *TypeLiteralNodeNode, body *ModuleBody) *Node { - if modifiers != node.modifiers || keyword != node.Keyword || name != node.name || attributes != node.Attributes || body != node.Body { + if modifiers != node.modifiers.get() || keyword != node.Keyword || name != node.name.get() || attributes != node.Attributes() || body != node.Body() { return updateNode(f.NewModuleDeclaration(modifiers, keyword, name, attributes, body), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ModuleDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.name) || - visit(v, node.Attributes) || - visit(v, node.Body) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.name.get()) || + visit(v, node.Attributes()) || + visit(v, node.Body()) } func (node *ModuleDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateModuleDeclaration(node, v.visitModifiers(node.modifiers), node.Keyword, v.visitNode(node.name), v.visitNode(node.Attributes), v.visitNode(node.Body)) + return v.Factory.UpdateModuleDeclaration(node, v.visitModifiers(node.modifiers.get()), node.Keyword, v.visitNode(node.name.get()), v.visitNode(node.Attributes()), v.visitNode(node.Body())) } func (node *ModuleDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewModuleDeclaration(node.Modifiers(), node.Keyword, node.name, node.Attributes, node.Body), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewModuleDeclaration(node.Modifiers(), node.Keyword, node.name.get(), node.Attributes(), node.Body()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ModuleDeclaration) Name() *DeclarationName { - return node.name + return node.name.get() } func IsModuleDeclaration(node *Node) bool { @@ -8097,40 +9225,48 @@ type ImportEqualsDeclaration struct { ModifiersBase CompositeBase IsTypeOnly bool - name *IdentifierNode - ModuleReference *ModuleReference + name link[Node] // *IdentifierNode + moduleReference link[Node] // *ModuleReference +} + +func (node *ImportEqualsDeclaration) ModuleReference() *ModuleReference { + return node.moduleReference.get() +} + +func (node *ImportEqualsDeclaration) SetModuleReference(moduleReference *ModuleReference) { + node.moduleReference.set(moduleReference) } func (f *NodeFactory) NewImportEqualsDeclaration(modifiers *ModifierList, isTypeOnly bool, name *IdentifierNode, moduleReference *ModuleReference) *Node { - data := &ImportEqualsDeclaration{} - data.modifiers = modifiers + data := newData[ImportEqualsDeclaration](f) + data.modifiers.set(modifiers) data.IsTypeOnly = isTypeOnly - data.name = name - data.ModuleReference = moduleReference + data.name.set(name) + data.moduleReference.set(moduleReference) return f.newNode(KindImportEqualsDeclaration, data) } func (f *NodeFactory) UpdateImportEqualsDeclaration(node *ImportEqualsDeclaration, modifiers *ModifierList, isTypeOnly bool, name *IdentifierNode, moduleReference *ModuleReference) *Node { - if modifiers != node.modifiers || isTypeOnly != node.IsTypeOnly || name != node.name || moduleReference != node.ModuleReference { + if modifiers != node.modifiers.get() || isTypeOnly != node.IsTypeOnly || name != node.name.get() || moduleReference != node.ModuleReference() { return updateNode(f.NewImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ImportEqualsDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || visit(v, node.name) || visit(v, node.ModuleReference) + return visitModifiers(v, node.modifiers.get()) || visit(v, node.name.get()) || visit(v, node.ModuleReference()) } func (node *ImportEqualsDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateImportEqualsDeclaration(node, v.visitModifiers(node.modifiers), node.IsTypeOnly, v.visitNode(node.name), v.visitNode(node.ModuleReference)) + return v.Factory.UpdateImportEqualsDeclaration(node, v.visitModifiers(node.modifiers.get()), node.IsTypeOnly, v.visitNode(node.name.get()), v.visitNode(node.ModuleReference())) } func (node *ImportEqualsDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewImportEqualsDeclaration(node.Modifiers(), node.IsTypeOnly, node.name, node.ModuleReference), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewImportEqualsDeclaration(node.Modifiers(), node.IsTypeOnly, node.name.get(), node.ModuleReference()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ImportEqualsDeclaration) Name() *DeclarationName { - return node.name + return node.name.get() } func IsImportEqualsDeclaration(node *Node) bool { @@ -8147,41 +9283,59 @@ type ExportDeclaration struct { ModifiersBase CompositeBase IsTypeOnly bool - ExportClause *NamedExportBindings // Optional - ModuleSpecifier *Expression // Optional - Attributes *ImportAttributesNode // Optional + exportClause link[Node] // *NamedExportBindings. Optional + moduleSpecifier link[Node] // *Expression. Optional + attributes link[Node] // *ImportAttributesNode. Optional +} + +func (node *ExportDeclaration) ExportClause() *NamedExportBindings { return node.exportClause.get() } + +func (node *ExportDeclaration) SetExportClause(exportClause *NamedExportBindings) { + node.exportClause.set(exportClause) +} + +func (node *ExportDeclaration) ModuleSpecifier() *Expression { return node.moduleSpecifier.get() } + +func (node *ExportDeclaration) SetModuleSpecifier(moduleSpecifier *Expression) { + node.moduleSpecifier.set(moduleSpecifier) +} + +func (node *ExportDeclaration) Attributes() *ImportAttributesNode { return node.attributes.get() } + +func (node *ExportDeclaration) SetAttributes(attributes *ImportAttributesNode) { + node.attributes.set(attributes) } func (f *NodeFactory) NewExportDeclaration(modifiers *ModifierList, isTypeOnly bool, exportClause *NamedExportBindings, moduleSpecifier *Expression, attributes *ImportAttributesNode) *Node { - data := &ExportDeclaration{} - data.modifiers = modifiers + data := newData[ExportDeclaration](f) + data.modifiers.set(modifiers) data.IsTypeOnly = isTypeOnly - data.ExportClause = exportClause - data.ModuleSpecifier = moduleSpecifier - data.Attributes = attributes + data.exportClause.set(exportClause) + data.moduleSpecifier.set(moduleSpecifier) + data.attributes.set(attributes) return f.newNode(KindExportDeclaration, data) } func (f *NodeFactory) UpdateExportDeclaration(node *ExportDeclaration, modifiers *ModifierList, isTypeOnly bool, exportClause *NamedExportBindings, moduleSpecifier *Expression, attributes *ImportAttributesNode) *Node { - if modifiers != node.modifiers || isTypeOnly != node.IsTypeOnly || exportClause != node.ExportClause || moduleSpecifier != node.ModuleSpecifier || attributes != node.Attributes { + if modifiers != node.modifiers.get() || isTypeOnly != node.IsTypeOnly || exportClause != node.ExportClause() || moduleSpecifier != node.ModuleSpecifier() || attributes != node.Attributes() { return updateNode(f.NewExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, attributes), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ExportDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.ExportClause) || - visit(v, node.ModuleSpecifier) || - visit(v, node.Attributes) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.ExportClause()) || + visit(v, node.ModuleSpecifier()) || + visit(v, node.Attributes()) } func (node *ExportDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateExportDeclaration(node, v.visitModifiers(node.modifiers), node.IsTypeOnly, v.visitNode(node.ExportClause), v.visitNode(node.ModuleSpecifier), v.visitNode(node.Attributes)) + return v.Factory.UpdateExportDeclaration(node, v.visitModifiers(node.modifiers.get()), node.IsTypeOnly, v.visitNode(node.ExportClause()), v.visitNode(node.ModuleSpecifier()), v.visitNode(node.Attributes())) } func (node *ExportDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewExportDeclaration(node.Modifiers(), node.IsTypeOnly, node.ExportClause, node.ModuleSpecifier, node.Attributes), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewExportDeclaration(node.Modifiers(), node.IsTypeOnly, node.ExportClause(), node.ModuleSpecifier(), node.Attributes()), node.AsNode(), f.AsNodeFactory().hooks) } func IsExportDeclaration(node *Node) bool { @@ -8195,41 +9349,55 @@ func IsExportDeclaration(node *Node) bool { type ImportTypeNode struct { NodeWithTypeArgumentsBase IsTypeOf bool - Argument *TypeNode - Attributes *ImportAttributesNode // Optional - Qualifier *EntityName // Optional + argument link[Node] // *TypeNode + attributes link[Node] // *ImportAttributesNode. Optional + qualifier link[Node] // *EntityName. Optional +} + +func (node *ImportTypeNode) Argument() *TypeNode { return node.argument.get() } + +func (node *ImportTypeNode) SetArgument(argument *TypeNode) { node.argument.set(argument) } + +func (node *ImportTypeNode) Attributes() *ImportAttributesNode { return node.attributes.get() } + +func (node *ImportTypeNode) SetAttributes(attributes *ImportAttributesNode) { + node.attributes.set(attributes) } +func (node *ImportTypeNode) Qualifier() *EntityName { return node.qualifier.get() } + +func (node *ImportTypeNode) SetQualifier(qualifier *EntityName) { node.qualifier.set(qualifier) } + func (f *NodeFactory) NewImportTypeNode(isTypeOf bool, argument *TypeNode, attributes *ImportAttributesNode, qualifier *EntityName, typeArguments *TypeList) *Node { - data := &ImportTypeNode{} + data := newData[ImportTypeNode](f) data.IsTypeOf = isTypeOf - data.Argument = argument - data.Attributes = attributes - data.Qualifier = qualifier - data.TypeArguments = typeArguments + data.argument.set(argument) + data.attributes.set(attributes) + data.qualifier.set(qualifier) + data.typeArguments.set(typeArguments) return f.newNode(KindImportType, data) } func (f *NodeFactory) UpdateImportTypeNode(node *ImportTypeNode, isTypeOf bool, argument *TypeNode, attributes *ImportAttributesNode, qualifier *EntityName, typeArguments *TypeList) *Node { - if isTypeOf != node.IsTypeOf || argument != node.Argument || attributes != node.Attributes || qualifier != node.Qualifier || typeArguments != node.TypeArguments { + if isTypeOf != node.IsTypeOf || argument != node.Argument() || attributes != node.Attributes() || qualifier != node.Qualifier() || typeArguments != node.TypeArguments() { return updateNode(f.NewImportTypeNode(isTypeOf, argument, attributes, qualifier, typeArguments), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ImportTypeNode) ForEachChild(v Visitor) bool { - return visit(v, node.Argument) || - visit(v, node.Attributes) || - visit(v, node.Qualifier) || - visitNodeList(v, node.TypeArguments) + return visit(v, node.Argument()) || + visit(v, node.Attributes()) || + visit(v, node.Qualifier()) || + visitNodeList(v, node.TypeArguments()) } func (node *ImportTypeNode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateImportTypeNode(node, node.IsTypeOf, v.visitNode(node.Argument), v.visitNode(node.Attributes), v.visitNode(node.Qualifier), v.visitNodes(node.TypeArguments)) + return v.Factory.UpdateImportTypeNode(node, node.IsTypeOf, v.visitNode(node.Argument()), v.visitNode(node.Attributes()), v.visitNode(node.Qualifier()), v.visitNodes(node.TypeArguments())) } func (node *ImportTypeNode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewImportTypeNode(node.IsTypeOf, node.Argument, node.Attributes, node.Qualifier, node.TypeArguments), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewImportTypeNode(node.IsTypeOf, node.Argument(), node.Attributes(), node.Qualifier(), node.TypeArguments()), node.AsNode(), f.AsNodeFactory().hooks) } func IsImportTypeNode(node *Node) bool { @@ -8246,39 +9414,45 @@ type ImportClause struct { ExportableBase CompositeBase PhaseModifier ImportPhaseModifierSyntaxKind // Optional - name *IdentifierNode // Optional - NamedBindings *NamedImportBindings // Optional + name link[Node] // *IdentifierNode. Optional + namedBindings link[Node] // *NamedImportBindings. Optional +} + +func (node *ImportClause) NamedBindings() *NamedImportBindings { return node.namedBindings.get() } + +func (node *ImportClause) SetNamedBindings(namedBindings *NamedImportBindings) { + node.namedBindings.set(namedBindings) } func (f *NodeFactory) NewImportClause(phaseModifier ImportPhaseModifierSyntaxKind, name *IdentifierNode, namedBindings *NamedImportBindings) *Node { - data := &ImportClause{} + data := newData[ImportClause](f) data.PhaseModifier = phaseModifier - data.name = name - data.NamedBindings = namedBindings + data.name.set(name) + data.namedBindings.set(namedBindings) return f.newNode(KindImportClause, data) } func (f *NodeFactory) UpdateImportClause(node *ImportClause, phaseModifier ImportPhaseModifierSyntaxKind, name *IdentifierNode, namedBindings *NamedImportBindings) *Node { - if phaseModifier != node.PhaseModifier || name != node.name || namedBindings != node.NamedBindings { + if phaseModifier != node.PhaseModifier || name != node.name.get() || namedBindings != node.NamedBindings() { return updateNode(f.NewImportClause(phaseModifier, name, namedBindings), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ImportClause) ForEachChild(v Visitor) bool { - return visit(v, node.name) || visit(v, node.NamedBindings) + return visit(v, node.name.get()) || visit(v, node.NamedBindings()) } func (node *ImportClause) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateImportClause(node, node.PhaseModifier, v.visitNode(node.name), v.visitNode(node.NamedBindings)) + return v.Factory.UpdateImportClause(node, node.PhaseModifier, v.visitNode(node.name.get()), v.visitNode(node.NamedBindings())) } func (node *ImportClause) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewImportClause(node.PhaseModifier, node.name, node.NamedBindings), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewImportClause(node.PhaseModifier, node.name.get(), node.NamedBindings()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ImportClause) Name() *DeclarationName { - return node.name + return node.name.get() } func IsImportClause(node *Node) bool { @@ -8295,39 +9469,45 @@ type ImportSpecifier struct { ExportableBase CompositeBase IsTypeOnly bool - PropertyName *ModuleExportName // Optional - name *IdentifierNode + propertyName link[Node] // *ModuleExportName. Optional + name link[Node] // *IdentifierNode +} + +func (node *ImportSpecifier) PropertyName() *ModuleExportName { return node.propertyName.get() } + +func (node *ImportSpecifier) SetPropertyName(propertyName *ModuleExportName) { + node.propertyName.set(propertyName) } func (f *NodeFactory) NewImportSpecifier(isTypeOnly bool, propertyName *ModuleExportName, name *IdentifierNode) *Node { - data := f.importSpecifierArena.New() + data := newData[ImportSpecifier](f) data.IsTypeOnly = isTypeOnly - data.PropertyName = propertyName - data.name = name + data.propertyName.set(propertyName) + data.name.set(name) return f.newNode(KindImportSpecifier, data) } func (f *NodeFactory) UpdateImportSpecifier(node *ImportSpecifier, isTypeOnly bool, propertyName *ModuleExportName, name *IdentifierNode) *Node { - if isTypeOnly != node.IsTypeOnly || propertyName != node.PropertyName || name != node.name { + if isTypeOnly != node.IsTypeOnly || propertyName != node.PropertyName() || name != node.name.get() { return updateNode(f.NewImportSpecifier(isTypeOnly, propertyName, name), node.AsNode(), f.hooks) } return node.AsNode() } func (node *ImportSpecifier) ForEachChild(v Visitor) bool { - return visit(v, node.PropertyName) || visit(v, node.name) + return visit(v, node.PropertyName()) || visit(v, node.name.get()) } func (node *ImportSpecifier) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateImportSpecifier(node, node.IsTypeOnly, v.visitNode(node.PropertyName), v.visitNode(node.name)) + return v.Factory.UpdateImportSpecifier(node, node.IsTypeOnly, v.visitNode(node.PropertyName()), v.visitNode(node.name.get())) } func (node *ImportSpecifier) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewImportSpecifier(node.IsTypeOnly, node.PropertyName, node.name), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewImportSpecifier(node.IsTypeOnly, node.PropertyName(), node.name.get()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *ImportSpecifier) Name() *DeclarationName { - return node.name + return node.name.get() } func IsImportSpecifier(node *Node) bool { @@ -8343,8 +9523,9 @@ type JSDocText struct { } func (f *NodeFactory) NewJSDocText(text []string) *Node { - data := f.jsdocTextArena.New() + data := newData[JSDocText](f) data.text = text + keepSlice(f, text) f.textCount++ return f.newNode(KindJSDocText, data) } @@ -8363,38 +9544,39 @@ func IsJSDocText(node *Node) bool { type JSDocLink struct { JSDocCommentBase - name *EntityName // Optional + name link[Node] // *EntityName. Optional } func (f *NodeFactory) NewJSDocLink(name *EntityName, text []string) *Node { - data := &JSDocLink{} - data.name = name + data := newData[JSDocLink](f) + data.name.set(name) data.text = text + keepSlice(f, text) f.textCount++ return f.newNode(KindJSDocLink, data) } func (f *NodeFactory) UpdateJSDocLink(node *JSDocLink, name *EntityName, text []string) *Node { - if name != node.name || !core.Same(text, node.text) { + if name != node.name.get() || !core.Same(text, node.text) { return updateNode(f.NewJSDocLink(name, text), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocLink) ForEachChild(v Visitor) bool { - return visit(v, node.name) + return visit(v, node.name.get()) } func (node *JSDocLink) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocLink(node, v.visitNode(node.name), node.text) + return v.Factory.UpdateJSDocLink(node, v.visitNode(node.name.get()), node.text) } func (node *JSDocLink) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocLink(node.name, node.text), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocLink(node.name.get(), node.text), node.AsNode(), f.AsNodeFactory().hooks) } func (node *JSDocLink) Name() *DeclarationName { - return node.name + return node.name.get() } func IsJSDocLink(node *Node) bool { @@ -8407,38 +9589,39 @@ func IsJSDocLink(node *Node) bool { type JSDocLinkPlain struct { JSDocCommentBase - name *EntityName // Optional + name link[Node] // *EntityName. Optional } func (f *NodeFactory) NewJSDocLinkPlain(name *EntityName, text []string) *Node { - data := &JSDocLinkPlain{} - data.name = name + data := newData[JSDocLinkPlain](f) + data.name.set(name) data.text = text + keepSlice(f, text) f.textCount++ return f.newNode(KindJSDocLinkPlain, data) } func (f *NodeFactory) UpdateJSDocLinkPlain(node *JSDocLinkPlain, name *EntityName, text []string) *Node { - if name != node.name || !core.Same(text, node.text) { + if name != node.name.get() || !core.Same(text, node.text) { return updateNode(f.NewJSDocLinkPlain(name, text), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocLinkPlain) ForEachChild(v Visitor) bool { - return visit(v, node.name) + return visit(v, node.name.get()) } func (node *JSDocLinkPlain) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocLinkPlain(node, v.visitNode(node.name), node.text) + return v.Factory.UpdateJSDocLinkPlain(node, v.visitNode(node.name.get()), node.text) } func (node *JSDocLinkPlain) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocLinkPlain(node.name, node.text), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocLinkPlain(node.name.get(), node.text), node.AsNode(), f.AsNodeFactory().hooks) } func (node *JSDocLinkPlain) Name() *DeclarationName { - return node.name + return node.name.get() } func IsJSDocLinkPlain(node *Node) bool { @@ -8451,38 +9634,39 @@ func IsJSDocLinkPlain(node *Node) bool { type JSDocLinkCode struct { JSDocCommentBase - name *EntityName // Optional + name link[Node] // *EntityName. Optional } func (f *NodeFactory) NewJSDocLinkCode(name *EntityName, text []string) *Node { - data := &JSDocLinkCode{} - data.name = name + data := newData[JSDocLinkCode](f) + data.name.set(name) data.text = text + keepSlice(f, text) f.textCount++ return f.newNode(KindJSDocLinkCode, data) } func (f *NodeFactory) UpdateJSDocLinkCode(node *JSDocLinkCode, name *EntityName, text []string) *Node { - if name != node.name || !core.Same(text, node.text) { + if name != node.name.get() || !core.Same(text, node.text) { return updateNode(f.NewJSDocLinkCode(name, text), node.AsNode(), f.hooks) } return node.AsNode() } func (node *JSDocLinkCode) ForEachChild(v Visitor) bool { - return visit(v, node.name) + return visit(v, node.name.get()) } func (node *JSDocLinkCode) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateJSDocLinkCode(node, v.visitNode(node.name), node.text) + return v.Factory.UpdateJSDocLinkCode(node, v.visitNode(node.name.get()), node.text) } func (node *JSDocLinkCode) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocLinkCode(node.name, node.text), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocLinkCode(node.name.get(), node.text), node.AsNode(), f.AsNodeFactory().hooks) } func (node *JSDocLinkCode) Name() *DeclarationName { - return node.name + return node.name.get() } func IsJSDocLinkCode(node *Node) bool { @@ -8498,47 +9682,65 @@ type TypeParameterDeclaration struct { NodeBase DeclarationBase ModifiersBase - name *IdentifierNode - Constraint *TypeNode // Optional - Expression *Expression // Optional - DefaultType *TypeNode // Optional + name link[Node] // *IdentifierNode + constraint link[Node] // *TypeNode. Optional + expression link[Node] // *Expression. Optional + defaultType link[Node] // *TypeNode. Optional +} + +func (node *TypeParameterDeclaration) Constraint() *TypeNode { return node.constraint.get() } + +func (node *TypeParameterDeclaration) SetConstraint(constraint *TypeNode) { + node.constraint.set(constraint) +} + +func (node *TypeParameterDeclaration) Expression() *Expression { return node.expression.get() } + +func (node *TypeParameterDeclaration) SetExpression(expression *Expression) { + node.expression.set(expression) +} + +func (node *TypeParameterDeclaration) DefaultType() *TypeNode { return node.defaultType.get() } + +func (node *TypeParameterDeclaration) SetDefaultType(defaultType *TypeNode) { + node.defaultType.set(defaultType) } func (f *NodeFactory) NewTypeParameterDeclaration(modifiers *ModifierList, name *IdentifierNode, constraint *TypeNode, expression *Expression, defaultType *TypeNode) *Node { - data := f.typeParameterDeclarationArena.New() - data.modifiers = modifiers - data.name = name - data.Constraint = constraint - data.Expression = expression - data.DefaultType = defaultType + data := newData[TypeParameterDeclaration](f) + data.modifiers.set(modifiers) + data.name.set(name) + data.constraint.set(constraint) + data.expression.set(expression) + data.defaultType.set(defaultType) return f.newNode(KindTypeParameter, data) } func (f *NodeFactory) UpdateTypeParameterDeclaration(node *TypeParameterDeclaration, modifiers *ModifierList, name *IdentifierNode, constraint *TypeNode, expression *Expression, defaultType *TypeNode) *Node { - if modifiers != node.modifiers || name != node.name || constraint != node.Constraint || expression != node.Expression || defaultType != node.DefaultType { + if modifiers != node.modifiers.get() || name != node.name.get() || constraint != node.Constraint() || expression != node.Expression() || defaultType != node.DefaultType() { return updateNode(f.NewTypeParameterDeclaration(modifiers, name, constraint, expression, defaultType), node.AsNode(), f.hooks) } return node.AsNode() } func (node *TypeParameterDeclaration) ForEachChild(v Visitor) bool { - return visitModifiers(v, node.modifiers) || - visit(v, node.name) || - visit(v, node.Constraint) || - visit(v, node.Expression) || - visit(v, node.DefaultType) + return visitModifiers(v, node.modifiers.get()) || + visit(v, node.name.get()) || + visit(v, node.Constraint()) || + visit(v, node.Expression()) || + visit(v, node.DefaultType()) } func (node *TypeParameterDeclaration) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateTypeParameterDeclaration(node, v.visitModifiers(node.modifiers), v.visitNode(node.name), v.visitNode(node.Constraint), v.visitNode(node.Expression), v.visitNode(node.DefaultType)) + return v.Factory.UpdateTypeParameterDeclaration(node, v.visitModifiers(node.modifiers.get()), v.visitNode(node.name.get()), v.visitNode(node.Constraint()), v.visitNode(node.Expression()), v.visitNode(node.DefaultType())) } func (node *TypeParameterDeclaration) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewTypeParameterDeclaration(node.Modifiers(), node.name, node.Constraint, node.Expression, node.DefaultType), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewTypeParameterDeclaration(node.Modifiers(), node.name.get(), node.Constraint(), node.Expression(), node.DefaultType()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *TypeParameterDeclaration) Name() *DeclarationName { - return node.name + return node.name.get() } func IsTypeParameterDeclaration(node *Node) bool { @@ -8551,39 +9753,49 @@ func IsTypeParameterDeclaration(node *Node) bool { type SyntheticReferenceExpression struct { ExpressionBase - Expression *Expression - ThisArg *Expression + expression link[Node] // *Expression + thisArg link[Node] // *Expression +} + +func (node *SyntheticReferenceExpression) Expression() *Expression { return node.expression.get() } + +func (node *SyntheticReferenceExpression) SetExpression(expression *Expression) { + node.expression.set(expression) } +func (node *SyntheticReferenceExpression) ThisArg() *Expression { return node.thisArg.get() } + +func (node *SyntheticReferenceExpression) SetThisArg(thisArg *Expression) { node.thisArg.set(thisArg) } + func (f *NodeFactory) NewSyntheticReferenceExpression(expression *Expression, thisArg *Expression) *Node { - data := &SyntheticReferenceExpression{} - data.Expression = expression - data.ThisArg = thisArg + data := newData[SyntheticReferenceExpression](f) + data.expression.set(expression) + data.thisArg.set(thisArg) return f.newNode(KindSyntheticReferenceExpression, data) } func (f *NodeFactory) UpdateSyntheticReferenceExpression(node *SyntheticReferenceExpression, expression *Expression, thisArg *Expression) *Node { - if expression != node.Expression || thisArg != node.ThisArg { + if expression != node.Expression() || thisArg != node.ThisArg() { return updateNode(f.NewSyntheticReferenceExpression(expression, thisArg), node.AsNode(), f.hooks) } return node.AsNode() } func (node *SyntheticReferenceExpression) ForEachChild(v Visitor) bool { - return visit(v, node.Expression) || visit(v, node.ThisArg) + return visit(v, node.Expression()) || visit(v, node.ThisArg()) } func (node *SyntheticReferenceExpression) VisitEachChild(v *NodeVisitor) *Node { - return v.Factory.UpdateSyntheticReferenceExpression(node, v.visitNode(node.Expression), v.visitNode(node.ThisArg)) + return v.Factory.UpdateSyntheticReferenceExpression(node, v.visitNode(node.Expression()), v.visitNode(node.ThisArg())) } func (node *SyntheticReferenceExpression) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewSyntheticReferenceExpression(node.Expression, node.ThisArg), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewSyntheticReferenceExpression(node.Expression(), node.ThisArg()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *SyntheticReferenceExpression) computeSubtreeFacts() SubtreeFacts { - return propagateSubtreeFacts(node.Expression) | - propagateSubtreeFacts(node.ThisArg) + return propagateSubtreeFacts(node.Expression()) | + propagateSubtreeFacts(node.ThisArg()) } func IsSyntheticReferenceExpression(node *Node) bool { @@ -8602,8 +9814,9 @@ type JSDocTypeLiteral struct { } func (f *NodeFactory) NewJSDocTypeLiteral(jsdocPropertyTags []*Node, isArrayType bool) *Node { - data := &JSDocTypeLiteral{} + data := newData[JSDocTypeLiteral](f) data.JSDocPropertyTags = jsdocPropertyTags + f.keepNodes(jsdocPropertyTags) data.IsArrayType = isArrayType return f.newNode(KindJSDocTypeLiteral, data) } @@ -8638,25 +9851,31 @@ func IsJSDocTypeLiteral(node *Node) bool { type JSDocParameterOrPropertyTag struct { JSDocTagBase - name *EntityName + name link[Node] // *EntityName IsBracketed bool - TypeExpression *TypeNode // Optional + typeExpression link[Node] // *TypeNode. Optional IsNameFirst bool } +func (node *JSDocParameterOrPropertyTag) TypeExpression() *TypeNode { return node.typeExpression.get() } + +func (node *JSDocParameterOrPropertyTag) SetTypeExpression(typeExpression *TypeNode) { + node.typeExpression.set(typeExpression) +} + func (f *NodeFactory) NewJSDocParameterOrPropertyTag(kind Kind, tagName *IdentifierNode, name *EntityName, isBracketed bool, typeExpression *TypeNode, isNameFirst bool, comment *NodeList) *Node { - data := &JSDocParameterOrPropertyTag{} - data.TagName = tagName - data.name = name + data := newData[JSDocParameterOrPropertyTag](f) + data.tagName.set(tagName) + data.name.set(name) data.IsBracketed = isBracketed - data.TypeExpression = typeExpression + data.typeExpression.set(typeExpression) data.IsNameFirst = isNameFirst - data.Comment = comment + data.comment.set(comment) return f.newNode(kind, data) } func (f *NodeFactory) UpdateJSDocParameterOrPropertyTag(node *JSDocParameterOrPropertyTag, tagName *IdentifierNode, name *EntityName, isBracketed bool, typeExpression *TypeNode, isNameFirst bool, comment *NodeList) *Node { - if tagName != node.TagName || name != node.name || isBracketed != node.IsBracketed || typeExpression != node.TypeExpression || isNameFirst != node.IsNameFirst || comment != node.Comment { + if tagName != node.TagName() || name != node.name.get() || isBracketed != node.IsBracketed || typeExpression != node.TypeExpression() || isNameFirst != node.IsNameFirst || comment != node.Comment() { return updateNode(f.NewJSDocParameterOrPropertyTag(node.Kind, tagName, name, isBracketed, typeExpression, isNameFirst, comment), node.AsNode(), f.hooks) } return node.AsNode() @@ -8671,11 +9890,11 @@ func (node *JSDocParameterOrPropertyTag) VisitEachChild(v *NodeVisitor) *Node { } func (node *JSDocParameterOrPropertyTag) Clone(f NodeFactoryCoercible) *Node { - return cloneNode(f.AsNodeFactory().NewJSDocParameterOrPropertyTag(node.Kind, node.TagName, node.name, node.IsBracketed, node.TypeExpression, node.IsNameFirst, node.Comment), node.AsNode(), f.AsNodeFactory().hooks) + return cloneNode(f.AsNodeFactory().NewJSDocParameterOrPropertyTag(node.Kind, node.TagName(), node.name.get(), node.IsBracketed, node.TypeExpression(), node.IsNameFirst, node.Comment()), node.AsNode(), f.AsNodeFactory().hooks) } func (node *JSDocParameterOrPropertyTag) Name() *DeclarationName { - return node.name + return node.name.get() } func IsJSDocParameterTag(node *Node) bool { diff --git a/tsc/internal/ast/functionflags.go b/tsc/internal/ast/functionflags.go index 431d40b585cda..911e0ba076b1f 100644 --- a/tsc/internal/ast/functionflags.go +++ b/tsc/internal/ast/functionflags.go @@ -21,7 +21,7 @@ func GetFunctionFlags(node *Node) FunctionFlags { flags := FunctionFlagsNormal switch node.Kind { case KindFunctionDeclaration, KindFunctionExpression, KindMethodDeclaration: - if data.AsteriskToken != nil { + if data.AsteriskToken() != nil { flags |= FunctionFlagsGenerator } fallthrough @@ -30,7 +30,7 @@ func GetFunctionFlags(node *Node) FunctionFlags { flags |= FunctionFlagsAsync } } - if data.Body == nil { + if data.Body() == nil { flags |= FunctionFlagsInvalid } return flags diff --git a/tsc/internal/ast/parseoptions.go b/tsc/internal/ast/parseoptions.go index 0070230b62b8c..d8a9fcc9fbf3a 100644 --- a/tsc/internal/ast/parseoptions.go +++ b/tsc/internal/ast/parseoptions.go @@ -94,7 +94,7 @@ func isFileProbablyExternalModule(sourceFile *SourceFile) *Node { func isAnExternalModuleIndicatorNode(node *Node) bool { return HasSyntacticModifier(node, ModifierFlagsExport) || - IsImportEqualsDeclaration(node) && IsExternalModuleReference(node.AsImportEqualsDeclaration().ModuleReference) || + IsImportEqualsDeclaration(node) && IsExternalModuleReference(node.AsImportEqualsDeclaration().ModuleReference()) || IsImportDeclaration(node) || IsExportAssignment(node) || IsExportDeclaration(node) } diff --git a/tsc/internal/ast/precedence.go b/tsc/internal/ast/precedence.go index bfaaa679b63af..e0ed38446a42a 100644 --- a/tsc/internal/ast/precedence.go +++ b/tsc/internal/ast/precedence.go @@ -189,7 +189,7 @@ const ( func getOperator(expression *Expression) Kind { switch expression.Kind { case KindBinaryExpression: - return expression.AsBinaryExpression().OperatorToken.Kind + return expression.AsBinaryExpression().OperatorToken().Kind case KindPrefixUnaryExpression: return expression.AsPrefixUnaryExpression().Operator case KindPostfixUnaryExpression: @@ -371,16 +371,16 @@ func GetLeftmostExpression(node *Expression, stopAtCallExpressions bool) *Expres for { switch node.Kind { case KindPostfixUnaryExpression: - node = node.AsPostfixUnaryExpression().Operand + node = node.AsPostfixUnaryExpression().Operand() continue case KindBinaryExpression: - node = node.AsBinaryExpression().Left + node = node.AsBinaryExpression().Left() continue case KindConditionalExpression: - node = node.AsConditionalExpression().Condition + node = node.AsConditionalExpression().Condition() continue case KindTaggedTemplateExpression: - node = node.AsTaggedTemplateExpression().Tag + node = node.AsTaggedTemplateExpression().Tag() continue case KindCallExpression: if stopAtCallExpressions { @@ -667,7 +667,7 @@ func GetTypeNodePrecedence(n *TypeNode) TypePrecedence { case KindTypeOperator: return TypePrecedenceTypeOperator case KindInferType: - if n.AsInferTypeNode().TypeParameter.AsTypeParameterDeclaration().Constraint != nil { + if n.AsInferTypeNode().TypeParameter().AsTypeParameterDeclaration().Constraint() != nil { // `infer T extends U` must be treated as FunctionTypeNode precedence as the `extends` clause eagerly consumes // TypeNode return TypePrecedenceFunction diff --git a/tsc/internal/ast/utilities.go b/tsc/internal/ast/utilities.go index 2644758d7372b..0e11909a49258 100644 --- a/tsc/internal/ast/utilities.go +++ b/tsc/internal/ast/utilities.go @@ -59,7 +59,12 @@ func GetExports(symbol *Symbol) SymbolTable { } func GetLocals(container *Node) SymbolTable { - return GetSymbolTable(&container.LocalsContainerData().Locals) + data := container.LocalsContainerData() + if data.Locals == nil { + data.Locals = make(SymbolTable) + keepSymbolTable(container, data.Locals) + } + return data.Locals } // Determines if a node is missing (either `nil` or empty) @@ -116,22 +121,22 @@ func IsCompoundAssignment(token Kind) bool { func IsAssignmentExpression(node *Node, excludeCompoundAssignment bool) bool { if node.Kind == KindBinaryExpression { expr := node.AsBinaryExpression() - return (expr.OperatorToken.Kind == KindEqualsToken || !excludeCompoundAssignment && IsAssignmentOperator(expr.OperatorToken.Kind)) && - IsLeftHandSideExpression(expr.Left) + return (expr.OperatorToken().Kind == KindEqualsToken || !excludeCompoundAssignment && IsAssignmentOperator(expr.OperatorToken().Kind)) && + IsLeftHandSideExpression(expr.Left()) } return false } func GetRightMostAssignedExpression(node *Node) *Node { for IsAssignmentExpression(node, false /*excludeCompoundAssignment*/) { - node = node.AsBinaryExpression().Right + node = node.AsBinaryExpression().Right() } return node } func IsDestructuringAssignment(node *Node) bool { if IsAssignmentExpression(node, true /*excludeCompoundAssignment*/) { - kind := node.AsBinaryExpression().Left.Kind + kind := node.AsBinaryExpression().Left().Kind return kind == KindObjectLiteralExpression || kind == KindArrayLiteralExpression } return false @@ -183,10 +188,10 @@ func IsAssignmentTarget(node *Node) bool { // the given node as an assignment target func GetAssignmentTarget(node *Node) *Node { for { - parent := node.Parent + parent := node.Parent() switch parent.Kind { case KindBinaryExpression: - if IsAssignmentOperator(parent.AsBinaryExpression().OperatorToken.Kind) && parent.AsBinaryExpression().Left == node { + if IsAssignmentOperator(parent.AsBinaryExpression().OperatorToken().Kind) && parent.AsBinaryExpression().Left() == node { return parent } return nil @@ -208,17 +213,17 @@ func GetAssignmentTarget(node *Node) *Node { case KindParenthesizedExpression, KindArrayLiteralExpression, KindSpreadElement, KindNonNullExpression: node = parent case KindSpreadAssignment: - node = parent.Parent + node = parent.Parent() case KindShorthandPropertyAssignment: if parent.AsShorthandPropertyAssignment().Name() != node { return nil } - node = parent.Parent + node = parent.Parent() case KindPropertyAssignment: if parent.AsPropertyAssignment().Name() == node { return nil } - node = parent.Parent + node = parent.Parent() default: return nil } @@ -234,11 +239,11 @@ func IsLogicalOrCoalescingBinaryOperator(token Kind) bool { } func IsLogicalOrCoalescingBinaryExpression(expr *Node) bool { - return IsBinaryExpression(expr) && IsLogicalOrCoalescingBinaryOperator(expr.AsBinaryExpression().OperatorToken.Kind) + return IsBinaryExpression(expr) && IsLogicalOrCoalescingBinaryOperator(expr.AsBinaryExpression().OperatorToken().Kind) } func IsLogicalOrCoalescingAssignmentExpression(expr *Node) bool { - return IsBinaryExpression(expr) && IsLogicalOrCoalescingAssignmentOperator(expr.AsBinaryExpression().OperatorToken.Kind) + return IsBinaryExpression(expr) && IsLogicalOrCoalescingAssignmentOperator(expr.AsBinaryExpression().OperatorToken().Kind) } func IsLogicalExpression(node *Node) bool { @@ -246,7 +251,7 @@ func IsLogicalExpression(node *Node) bool { if node.Kind == KindParenthesizedExpression { node = node.Expression() } else if node.Kind == KindPrefixUnaryExpression && node.AsPrefixUnaryExpression().Operator == KindExclamationToken { - node = node.AsPrefixUnaryExpression().Operand + node = node.AsPrefixUnaryExpression().Operand() } else { return IsLogicalOrCoalescingBinaryExpression(node) } @@ -290,13 +295,13 @@ func IsPropertyName(node *Node) bool { // Return true if the given identifier is classified as an IdentifierName by inspecting the parent of the node func IsIdentifierName(node *Node) bool { - parent := node.Parent + parent := node.Parent() switch parent.Kind { case KindPropertyDeclaration, KindPropertySignature, KindMethodDeclaration, KindMethodSignature, KindGetAccessor, KindSetAccessor, KindEnumMember, KindPropertyAssignment, KindPropertyAccessExpression: return parent.Name() == node case KindQualifiedName: - return parent.AsQualifiedName().Right == node + return parent.AsQualifiedName().Right() == node case KindBindingElement: return parent.PropertyName() == node case KindImportSpecifier: @@ -335,7 +340,7 @@ func IsStringOrNumericLiteralLike(node *Node) bool { func IsSignedNumericLiteral(node *Node) bool { if node.Kind == KindPrefixUnaryExpression { node := node.AsPrefixUnaryExpression() - return (node.Operator == KindPlusToken || node.Operator == KindMinusToken) && IsNumericLiteral(node.Operand) + return (node.Operator == KindPlusToken || node.Operator == KindMinusToken) && IsNumericLiteral(node.Operand()) } return false } @@ -373,7 +378,7 @@ func IsOptionalChainRoot(node *Expression) bool { // 5. For `a?.(b?.c).d`, both `b?.c` and `a?.(b?.c)d` are outermost (`c` is the end of the chain starting at `b`, and `d` is // the end of the chain starting at `a?.`) func IsOutermostOptionalChain(node *Expression) bool { - parent := node.Parent + parent := node.Parent() return !IsOptionalChain(parent) || // cases 1, 2, and 3 IsOptionalChainRoot(parent) || // case 4 node != parent.Expression() // case 5 @@ -381,11 +386,11 @@ func IsOutermostOptionalChain(node *Expression) bool { // Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`). func IsExpressionOfOptionalChainRoot(node *Node) bool { - return IsOptionalChainRoot(node.Parent) && node.Parent.Expression() == node + return IsOptionalChainRoot(node.Parent()) && node.Parent().Expression() == node } func IsNullishCoalesce(node *Node) bool { - return node.Kind == KindBinaryExpression && node.AsBinaryExpression().OperatorToken.Kind == KindQuestionQuestionToken + return node.Kind == KindBinaryExpression && node.AsBinaryExpression().OperatorToken().Kind == KindQuestionQuestionToken } func IsAssertionExpression(node *Node) bool { @@ -453,7 +458,7 @@ func IsExpression(node *Node) bool { } func IsCommaExpression(node *Node) bool { - return node.Kind == KindBinaryExpression && node.AsBinaryExpression().OperatorToken.Kind == KindCommaToken + return node.Kind == KindBinaryExpression && node.AsBinaryExpression().OperatorToken().Kind == KindCommaToken } func IsCommaSequence(node *Node) bool { @@ -566,7 +571,7 @@ func IsPrivateIdentifierClassElementDeclaration(node *Node) bool { func IsObjectLiteralOrClassExpressionMethodOrAccessor(node *Node) bool { kind := node.Kind return (kind == KindMethodDeclaration || kind == KindGetAccessor || kind == KindSetAccessor) && - (node.Parent.Kind == KindObjectLiteralExpression || node.Parent.Kind == KindClassExpression) + (node.Parent().Kind == KindObjectLiteralExpression || node.Parent().Kind == KindClassExpression) } func IsTypeElement(node *Node) bool { @@ -598,7 +603,7 @@ func IsObjectLiteralElement(node *Node) bool { } func IsObjectLiteralMethod(node *Node) bool { - return node != nil && node.Kind == KindMethodDeclaration && node.Parent.Kind == KindObjectLiteralExpression + return node != nil && node.Kind == KindMethodDeclaration && node.Parent().Kind == KindObjectLiteralExpression } func IsAutoAccessorPropertyDeclaration(node *Node) bool { @@ -703,7 +708,7 @@ func isBlockStatement(node *Node) bool { if node.Kind != KindBlock { return false } - if node.Parent != nil && (node.Parent.Kind == KindTryStatement || node.Parent.Kind == KindCatchClause) { + if node.Parent() != nil && (node.Parent().Kind == KindTryStatement || node.Parent().Kind == KindCatchClause) { return false } return !IsFunctionBlock(node) @@ -711,7 +716,7 @@ func isBlockStatement(node *Node) bool { // Determines whether a node is the Block-like body of a function by walking the parent of the node func IsFunctionBlock(node *Node) bool { - return node != nil && node.Kind == KindBlock && node.Parent != nil && IsFunctionLike(node.Parent) + return node != nil && node.Kind == KindBlock && node.Parent() != nil && IsFunctionLike(node.Parent()) } func IsBlockOrCatchScoped(declaration *Node) bool { @@ -720,7 +725,7 @@ func IsBlockOrCatchScoped(declaration *Node) bool { func IsCatchClauseVariableDeclarationOrBindingElement(declaration *Node) bool { node := GetRootDeclaration(declaration) - return node.Kind == KindVariableDeclaration && node.Parent.Kind == KindCatchClause + return node.Kind == KindVariableDeclaration && node.Parent().Kind == KindCatchClause } func IsTypeNodeKind(kind Kind) bool { @@ -803,7 +808,7 @@ func IsOuterExpression(node *Expression, kinds OuterExpressionKinds) bool { case KindPartiallyEmittedExpression: return kinds&OEKPartiallyEmittedExpressions != 0 case KindBinaryExpression: - switch node.AsBinaryExpression().OperatorToken.Kind { + switch node.AsBinaryExpression().OperatorToken().Kind { case KindEqualsToken: return kinds&OEKAssignments != 0 case KindCommaToken: @@ -817,7 +822,7 @@ func IsOuterExpression(node *Expression, kinds OuterExpressionKinds) bool { func SkipOuterExpressions(node *Expression, kinds OuterExpressionKinds) *Expression { for IsOuterExpression(node, kinds) { if IsBinaryExpression(node) { - node = node.AsBinaryExpression().Right + node = node.AsBinaryExpression().Right() } else { node = node.Expression() } @@ -844,7 +849,7 @@ func SkipPartiallyEmittedExpressions(node *Expression) *Expression { // Walks up the parents of a parenthesized expression to find the containing node func WalkUpParenthesizedExpressions(node *Expression) *Node { for node != nil && node.Kind == KindParenthesizedExpression { - node = node.Parent + node = node.Parent() } return node } @@ -852,7 +857,7 @@ func WalkUpParenthesizedExpressions(node *Expression) *Node { // Walks up the parents of a parenthesized type to find the containing node func WalkUpParenthesizedTypes(node *TypeNode) *Node { for node != nil && node.Kind == KindParenthesizedType { - node = node.Parent + node = node.Parent() } return node } @@ -863,7 +868,7 @@ func GetSourceFileOfNode(node *Node) *SourceFile { if node.Kind == KindSourceFile { return node.AsSourceFile() } - node = node.Parent + node = node.Parent() } return nil } @@ -884,7 +889,7 @@ func newParentInChildrenSetter() func(node *Node) bool { state.visit = func(node *Node) bool { if state.parent != nil { - node.Parent = state.parent + node.SetParent(state.parent) } saveParent := state.parent state.parent = node @@ -913,7 +918,7 @@ func FindAncestor(node *Node, callback func(*Node) bool) *Node { if callback(node) { return node } - node = node.Parent + node = node.Parent() } return nil } @@ -932,7 +937,7 @@ func FindManyAncestors(node *Node, callbacks ...func(*Node) bool) []*Node { break } } - node = node.Parent + node = node.Parent() } return ancestors } @@ -943,7 +948,7 @@ func FindAncestorKind(node *Node, kind Kind) *Node { if node.Kind == kind { return node } - node = node.Parent + node = node.Parent() } return nil } @@ -972,7 +977,7 @@ func FindAncestorOrQuit(node *Node, callback func(*Node) FindAncestorResult) *No case FindAncestorTrue: return node } - node = node.Parent + node = node.Parent() } return nil } @@ -982,7 +987,7 @@ func IsNodeDescendantOf(node *Node, ancestor *Node) bool { if node == ancestor { return true } - node = node.Parent + node = node.Parent() } return false } @@ -1145,7 +1150,7 @@ func CanHaveDecorators(node *Node) bool { } func IsFunctionOrModuleBlock(node *Node) bool { - return IsSourceFile(node) || IsModuleBlock(node) || IsBlock(node) && IsFunctionLike(node.Parent) + return IsSourceFile(node) || IsModuleBlock(node) || IsBlock(node) && IsFunctionLike(node.Parent()) } func IsFunctionExpressionOrArrowFunction(node *Node) bool { @@ -1172,7 +1177,7 @@ func ForEachReturnStatement(body *Node, visitor func(stmt *Node) bool) bool { func GetRootDeclaration(node *Node) *Node { for node.Kind == KindBindingElement { - node = node.Parent.Parent + node = node.Parent().Parent() } return node } @@ -1181,11 +1186,11 @@ func GetCombinedModifierFlags(node *Node) ModifierFlags { node = GetRootDeclaration(node) flags := node.ModifierFlags() if node.Kind == KindVariableDeclaration { - node = node.Parent + node = node.Parent() } if node != nil && node.Kind == KindVariableDeclarationList { flags |= node.ModifierFlags() - node = node.Parent + node = node.Parent() } if node != nil && node.Kind == KindVariableStatement { flags |= node.ModifierFlags() @@ -1197,11 +1202,11 @@ func GetCombinedNodeFlags(node *Node) NodeFlags { node = GetRootDeclaration(node) flags := node.Flags if node.Kind == KindVariableDeclaration { - node = node.Parent + node = node.Parent() } if node != nil && node.Kind == KindVariableDeclarationList { flags |= node.Flags - node = node.Parent + node = node.Parent() } if node != nil && node.Kind == KindVariableStatement { flags |= node.Flags @@ -1222,7 +1227,7 @@ func IsVarUsing(node *Node) bool { // GetJSDocDeprecatedTag returns the first @deprecated JSDoc tag for the given node, or nil if none exists. func GetJSDocDeprecatedTag(node *Node) *Node { for _, jsdoc := range node.JSDoc(nil) { - tags := jsdoc.AsJSDoc().Tags + tags := jsdoc.AsJSDoc().Tags() if tags != nil { for _, tag := range tags.Nodes { if IsJSDocDeprecatedTag(tag) { @@ -1249,7 +1254,7 @@ func IsDeprecatedDeclarationWithCachedFlags(declaration *Node, combinedFlags Nod } // Walk up to find the node that directly has the flag, since JSDoc is // attached to that node (e.g. VariableStatement, not VariableDeclaration). - for n := declaration; n != nil; n = n.Parent { + for n := declaration; n != nil; n = n.Parent() { if n.Flags&NodeFlagsPossiblyContainsDeprecatedTag != 0 { return GetJSDocDeprecatedTag(n) != nil } @@ -1284,11 +1289,11 @@ func IsImportMeta(node *Node) bool { } func WalkUpBindingElementsAndPatterns(binding *Node) *Node { - node := binding.Parent - for IsBindingElement(node.Parent) { - node = node.Parent.Parent + node := binding.Parent() + for IsBindingElement(node.Parent()) { + node = node.Parent().Parent() } - return node.Parent + return node.Parent() } func IsSourceFileJS(file *SourceFile) bool { @@ -1301,19 +1306,19 @@ func IsInJSFile(node *Node) bool { func IsDeclaration(node *Node) bool { if node.Kind == KindTypeParameter { - return node.Parent != nil + return node.Parent() != nil } return IsDeclarationNode(node) } // True if `name` is the name of a declaration node func IsDeclarationName(name *Node) bool { - return !IsSourceFile(name) && !IsBindingPattern(name) && IsDeclaration(name.Parent) && name.Parent.Name() == name + return !IsSourceFile(name) && !IsBindingPattern(name) && IsDeclaration(name.Parent()) && name.Parent().Name() == name } // Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. func IsDeclarationNameOrImportPropertyName(name *Node) bool { - switch name.Parent.Kind { + switch name.Parent().Kind { case KindImportSpecifier, KindExportSpecifier: return IsIdentifier(name) || name.Kind == KindStringLiteral default: @@ -1323,12 +1328,12 @@ func IsDeclarationNameOrImportPropertyName(name *Node) bool { func IsLiteralComputedPropertyDeclarationName(node *Node) bool { return IsStringOrNumericLiteralLike(node) && - node.Parent.Kind == KindComputedPropertyName && - IsDeclaration(node.Parent.Parent) + node.Parent().Kind == KindComputedPropertyName && + IsDeclaration(node.Parent().Parent()) } func IsExternalModuleImportEqualsDeclaration(node *Node) bool { - return node.Kind == KindImportEqualsDeclaration && node.AsImportEqualsDeclaration().ModuleReference.Kind == KindExternalModuleReference + return node.Kind == KindImportEqualsDeclaration && node.AsImportEqualsDeclaration().ModuleReference().Kind == KindExternalModuleReference } func IsModuleOrEnumDeclaration(node *Node) bool { @@ -1336,11 +1341,11 @@ func IsModuleOrEnumDeclaration(node *Node) bool { } func IsLiteralImportTypeNode(node *Node) bool { - return IsImportTypeNode(node) && IsLiteralTypeNode(node.AsImportTypeNode().Argument) && IsStringLiteral(node.AsImportTypeNode().Argument.AsLiteralTypeNode().Literal) + return IsImportTypeNode(node) && IsLiteralTypeNode(node.AsImportTypeNode().Argument()) && IsStringLiteral(node.AsImportTypeNode().Argument().AsLiteralTypeNode().Literal()) } func IsJsxTagName(node *Node) bool { - parent := node.Parent + parent := node.Parent() switch parent.Kind { case KindJsxOpeningElement, KindJsxClosingElement, KindJsxSelfClosingElement: return parent.TagName() == node @@ -1395,7 +1400,7 @@ func IsPrototypeAccess(node *Node) bool { } func IsLiteralLikeElementAccess(node *Node) bool { - return IsElementAccessExpression(node) && IsStringOrNumericLiteralLike(node.AsElementAccessExpression().ArgumentExpression) + return IsElementAccessExpression(node) && IsStringOrNumericLiteralLike(node.AsElementAccessExpression().ArgumentExpression()) } func IsBindableStaticNameExpression(node *Node, excludeThisKeyword bool) bool { @@ -1412,7 +1417,7 @@ func GetElementOrPropertyAccessName(node *Node) *Node { } return nil case KindElementAccessExpression: - if arg := SkipParentheses(node.AsElementAccessExpression().ArgumentExpression); IsStringOrNumericLiteralLike(arg) { + if arg := SkipParentheses(node.AsElementAccessExpression().ArgumentExpression()); IsStringOrNumericLiteralLike(arg) { return arg } return nil @@ -1421,10 +1426,10 @@ func GetElementOrPropertyAccessName(node *Node) *Node { } func GetInitializerOfBinaryExpression(expr *BinaryExpression) *Expression { - for IsBinaryExpression(expr.Right) { - expr = expr.Right.AsBinaryExpression() + for IsBinaryExpression(expr.Right()) { + expr = expr.Right().AsBinaryExpression() } - return expr.Right.Expression() + return expr.Right().Expression() } func IsExpressionWithTypeArgumentsInClassExtendsClause(node *Node) bool { @@ -1444,8 +1449,8 @@ func TryGetClassExtendingExpressionWithTypeArguments(node *Node) *ClassLikeDecla func TryGetClassImplementingOrExtendingHeritageClauseElement(node *Node) (class *ClassLikeDeclaration, isImplements bool) { if (IsExpressionWithTypeArguments(node) || IsTypeReferenceNode(node)) && - IsHeritageClause(node.Parent) && IsClassLike(node.Parent.Parent) { - return node.Parent.Parent, node.Parent.AsHeritageClause().Token == KindImplementsKeyword + IsHeritageClause(node.Parent()) && IsClassLike(node.Parent().Parent()) { + return node.Parent().Parent(), node.Parent().AsHeritageClause().Token == KindImplementsKeyword } return nil, false } @@ -1470,7 +1475,7 @@ func GetNonAssignedNameOfDeclaration(declaration *Node) *Node { case KindBinaryExpression, KindCallExpression: switch GetAssignmentDeclarationKind(declaration) { case JSDeclarationKindProperty, JSDeclarationKindThisProperty, JSDeclarationKindExportsProperty: - left := declaration.AsBinaryExpression().Left + left := declaration.AsBinaryExpression().Left() if name := GetElementOrPropertyAccessName(left); name != nil { return name } @@ -1490,7 +1495,7 @@ func GetNonAssignedNameOfDeclaration(declaration *Node) *Node { } func GetAssignedName(node *Node) *Node { - parent := node.Parent + parent := node.Parent() if parent != nil { switch parent.Kind { case KindPropertyAssignment: @@ -1498,15 +1503,15 @@ func GetAssignedName(node *Node) *Node { case KindBindingElement: return parent.AsBindingElement().Name() case KindBinaryExpression: - if node == parent.AsBinaryExpression().Right { - left := parent.AsBinaryExpression().Left + if node == parent.AsBinaryExpression().Right() { + left := parent.AsBinaryExpression().Left() switch left.Kind { case KindIdentifier: return left case KindPropertyAccessExpression: return left.AsPropertyAccessExpression().Name() case KindElementAccessExpression: - arg := SkipParentheses(left.AsElementAccessExpression().ArgumentExpression) + arg := SkipParentheses(left.AsElementAccessExpression().ArgumentExpression()) if IsStringOrNumericLiteralLike(arg) { return arg } @@ -1548,21 +1553,21 @@ func GetAssignmentDeclarationKind(node *Node) JSDeclarationKind { switch node.Kind { case KindBinaryExpression: bin := node.AsBinaryExpression() - if bin.OperatorToken.Kind == KindEqualsToken && IsAccessExpression(bin.Left) { - if IsInJSFile(bin.Left) { - if IsModuleExportsAccessExpression(bin.Left) && !IsExportsIdentifier(bin.Right) { + if bin.OperatorToken().Kind == KindEqualsToken && IsAccessExpression(bin.Left()) { + if IsInJSFile(bin.Left()) { + if IsModuleExportsAccessExpression(bin.Left()) && !IsExportsIdentifier(bin.Right()) { return JSDeclarationKindModuleExports } - if (IsModuleExportsAccessExpression(bin.Left.Expression()) || IsExportsIdentifier(bin.Left.Expression())) && - GetElementOrPropertyAccessName(bin.Left) != nil { + if (IsModuleExportsAccessExpression(bin.Left().Expression()) || IsExportsIdentifier(bin.Left().Expression())) && + GetElementOrPropertyAccessName(bin.Left()) != nil { return JSDeclarationKindExportsProperty } - if bin.Left.Expression().Kind == KindThisKeyword { + if bin.Left().Expression().Kind == KindThisKeyword { return JSDeclarationKindThisProperty } } - if bin.Left.Kind == KindPropertyAccessExpression && IsEntityNameExpressionEx(bin.Left.Expression(), IsInJSFile(bin.Left)) && IsIdentifier(bin.Left.Name()) || - bin.Left.Kind == KindElementAccessExpression && IsEntityNameExpressionEx(bin.Left.Expression(), IsInJSFile(bin.Left)) { + if bin.Left().Kind == KindPropertyAccessExpression && IsEntityNameExpressionEx(bin.Left().Expression(), IsInJSFile(bin.Left())) && IsIdentifier(bin.Left().Name()) || + bin.Left().Kind == KindElementAccessExpression && IsEntityNameExpressionEx(bin.Left().Expression(), IsInJSFile(bin.Left())) { return JSDeclarationKindProperty } } @@ -1610,7 +1615,7 @@ func IsDynamicName(name *Node) bool { case KindComputedPropertyName: expr = name.Expression() case KindElementAccessExpression: - expr = SkipParentheses(name.AsElementAccessExpression().ArgumentExpression) + expr = SkipParentheses(name.AsElementAccessExpression().ArgumentExpression()) default: return false } @@ -1632,7 +1637,7 @@ func IsPropertyAccessEntityNameExpression(node *Node, allowJS bool) bool { } func isElementAccessEntityNameExpression(node *Node, allowJS bool) bool { - return IsElementAccessExpression(node) && IsStringOrNumericLiteralLike(node.AsElementAccessExpression().ArgumentExpression) && IsEntityNameExpressionEx(node.Expression(), allowJS) + return IsElementAccessExpression(node) && IsStringOrNumericLiteralLike(node.AsElementAccessExpression().ArgumentExpression()) && IsEntityNameExpressionEx(node.Expression(), allowJS) } func IsDottedName(node *Node) bool { @@ -1708,7 +1713,7 @@ func IsExternalModuleIndicator(node *Statement) bool { func IsExportNamespaceAsDefaultDeclaration(node *Node) bool { if IsExportDeclaration(node) { decl := node.AsExportDeclaration() - return IsNamespaceExport(decl.ExportClause) && ModuleExportNameIsDefault(decl.ExportClause.Name()) + return IsNamespaceExport(decl.ExportClause()) && ModuleExportNameIsDefault(decl.ExportClause().Name()) } return false } @@ -1721,12 +1726,12 @@ func IsModuleAugmentationExternal(node *Node) bool { // external module augmentation is a ambient module declaration that is either: // - defined in the top level scope and source file is an external module // - defined inside ambient module declaration located in the top level scope and source file not an external module - switch node.Parent.Kind { + switch node.Parent().Kind { case KindSourceFile: - return IsExternalModule(node.Parent.AsSourceFile()) + return IsExternalModule(node.Parent().AsSourceFile()) case KindModuleBlock: - grandParent := node.Parent.Parent - return IsAmbientModule(grandParent) && IsSourceFile(grandParent.Parent) && !IsExternalModule(grandParent.Parent.AsSourceFile()) + grandParent := node.Parent().Parent() + return IsAmbientModule(grandParent) && IsSourceFile(grandParent.Parent()) && !IsExternalModule(grandParent.Parent().AsSourceFile()) } return false } @@ -1736,7 +1741,7 @@ func IsModuleWithStringLiteralName(node *Node) bool { } func GetContainingClass(node *Node) *Node { - return FindAncestor(node.Parent, IsClassLike) + return FindAncestor(node.Parent(), IsClassLike) } func GetExtendsHeritageClauseElements(node *Node) []*HeritageClauseElement { @@ -1750,7 +1755,7 @@ func GetImplementsHeritageClauseElements(node *Node) []*HeritageClauseElement { func GetHeritageElements(node *Node, kind Kind) []*HeritageClauseElement { clause := GetHeritageClause(node, kind) if clause != nil { - return clause.AsHeritageClause().Types.Nodes + return clause.AsHeritageClause().Types().Nodes } return nil } @@ -1758,18 +1763,18 @@ func GetHeritageElements(node *Node, kind Kind) []*HeritageClauseElement { // GetHeritageClauseElementName returns the expression or type name of a heritage clause element. func GetHeritageClauseElementName(node *HeritageClauseElement) *Node { if IsTypeReferenceNode(node) { - return node.AsTypeReferenceNode().TypeName + return node.AsTypeReferenceNode().TypeName() } - return node.AsExpressionWithTypeArguments().Expression + return node.AsExpressionWithTypeArguments().Expression() } func IsNameOfHeritageClauseTypeReference(node *Node) bool { - for IsQualifiedName(node.Parent) { - node = node.Parent + for IsQualifiedName(node.Parent()) { + node = node.Parent() } - return IsTypeReferenceNode(node.Parent) && - node.Parent.AsTypeReferenceNode().TypeName == node && - IsHeritageClause(node.Parent.Parent) + return IsTypeReferenceNode(node.Parent()) && + node.Parent().AsTypeReferenceNode().TypeName() == node && + IsHeritageClause(node.Parent().Parent()) } func GetHeritageClause(node *Node, kind Kind) *Node { @@ -1787,18 +1792,18 @@ func GetHeritageClause(node *Node, kind Kind) *Node { func getHeritageClauses(node *Node) *NodeList { switch node.Kind { case KindClassDeclaration: - return node.AsClassDeclaration().HeritageClauses + return node.AsClassDeclaration().HeritageClauses() case KindClassExpression: - return node.AsClassExpression().HeritageClauses + return node.AsClassExpression().HeritageClauses() case KindInterfaceDeclaration: - return node.AsInterfaceDeclaration().HeritageClauses + return node.AsInterfaceDeclaration().HeritageClauses() } return nil } func IsPartOfTypeQuery(node *Node) bool { for node.Kind == KindQualifiedName || node.Kind == KindIdentifier { - node = node.Parent + node = node.Parent() } return node.Kind == KindTypeQuery } @@ -1817,7 +1822,7 @@ func IsPartOfParameterDeclaration(node *Node) bool { func IsInTopLevelContext(node *Node) bool { // The name of a class or function declaration is a BindingIdentifier in its surrounding scope. if IsIdentifier(node) { - parent := node.Parent + parent := node.Parent() if (IsClassDeclaration(parent) || IsFunctionDeclaration(parent)) && parent.Name() == node { node = parent } @@ -1828,25 +1833,25 @@ func IsInTopLevelContext(node *Node) bool { func GetThisContainer(node *Node, includeArrowFunctions bool, includeClassComputedPropertyName bool) *Node { for { - node = node.Parent + node = node.Parent() if node == nil { panic("nil parent in getThisContainer") } switch node.Kind { case KindComputedPropertyName: - if includeClassComputedPropertyName && IsClassLike(node.Parent.Parent) { + if includeClassComputedPropertyName && IsClassLike(node.Parent().Parent()) { return node } - node = node.Parent.Parent + node = node.Parent().Parent() case KindDecorator: - if node.Parent.Kind == KindParameter && IsClassElement(node.Parent.Parent) { + if node.Parent().Kind == KindParameter && IsClassElement(node.Parent().Parent()) { // If the decorator's parent is a ParameterDeclaration, we resolve the this container from // the grandparent class declaration. - node = node.Parent.Parent - } else if IsClassElement(node.Parent) { + node = node.Parent().Parent() + } else if IsClassElement(node.Parent()) { // If the decorator's parent is a class element, we resolve the 'this' container // from the parent class declaration. - node = node.Parent + node = node.Parent() } case KindArrowFunction: if includeArrowFunctions { @@ -1862,10 +1867,10 @@ func GetThisContainer(node *Node, includeArrowFunctions bool, includeClassComput } func GetSuperContainer(node *Node, stopOnFunctions bool) *Node { - for node = node.Parent; node != nil; node = node.Parent { + for node = node.Parent(); node != nil; node = node.Parent() { switch node.Kind { case KindComputedPropertyName: - node = node.Parent + node = node.Parent() case KindFunctionDeclaration, KindFunctionExpression, KindArrowFunction: if !stopOnFunctions { continue @@ -1875,14 +1880,14 @@ func GetSuperContainer(node *Node, stopOnFunctions bool) *Node { return node case KindDecorator: // Decorators are always applied outside of the body of a class or method. - if node.Parent.Kind == KindParameter && IsClassElement(node.Parent.Parent) { + if node.Parent().Kind == KindParameter && IsClassElement(node.Parent().Parent()) { // If the decorator's parent is a ParameterDeclaration, we resolve the this container from // the grandparent class declaration. - node = node.Parent.Parent - } else if IsClassElement(node.Parent) { + node = node.Parent().Parent() + } else if IsClassElement(node.Parent()) { // If the decorator's parent is a class element, we resolve the 'this' container // from the parent class declaration. - node = node.Parent + node = node.Parent() } } } @@ -1892,10 +1897,10 @@ func GetSuperContainer(node *Node, stopOnFunctions bool) *Node { func GetImmediatelyInvokedFunctionExpression(fn *Node) *Node { if IsFunctionExpressionOrArrowFunction(fn) { prev := fn - parent := fn.Parent + parent := fn.Parent() for IsParenthesizedExpression(parent) { prev = parent - parent = parent.Parent + parent = parent.Parent() } if IsCallExpression(parent) && parent.Expression() == prev { return parent @@ -1913,7 +1918,7 @@ func ExpressionIsAlias(node *Node) bool { } func IsInstanceOfExpression(node *Node) bool { - return IsBinaryExpression(node) && node.AsBinaryExpression().OperatorToken.Kind == KindInstanceOfKeyword + return IsBinaryExpression(node) && node.AsBinaryExpression().OperatorToken().Kind == KindInstanceOfKeyword } func IsAnyImportOrReExport(node *Node) bool { @@ -1944,8 +1949,8 @@ func GetExternalModuleName(node *Node) *Expression { case KindImportDeclaration, KindJSImportDeclaration, KindExportDeclaration: return node.ModuleSpecifier() case KindImportEqualsDeclaration: - if node.AsImportEqualsDeclaration().ModuleReference.Kind == KindExternalModuleReference { - return node.AsImportEqualsDeclaration().ModuleReference.Expression() + if node.AsImportEqualsDeclaration().ModuleReference().Kind == KindExternalModuleReference { + return node.AsImportEqualsDeclaration().ModuleReference().Expression() } return nil case KindImportType: @@ -1972,11 +1977,11 @@ func HasImportAttributes(node *Node) bool { func GetImportAttributes(node *Node) *Node { switch node.Kind { case KindImportDeclaration, KindJSImportDeclaration: - return node.AsImportDeclaration().Attributes + return node.AsImportDeclaration().Attributes() case KindExportDeclaration: - return node.AsExportDeclaration().Attributes + return node.AsExportDeclaration().Attributes() case KindImportType: - return node.AsImportTypeNode().Attributes + return node.AsImportTypeNode().Attributes() } panic("Unhandled case in getImportAttributes: " + node.Kind.String()) } @@ -1984,10 +1989,10 @@ func GetImportAttributes(node *Node) *Node { func getImportTypeNodeLiteral(node *Node) *Node { if IsImportTypeNode(node) { importTypeNode := node.AsImportTypeNode() - if IsLiteralTypeNode(importTypeNode.Argument) { - literalTypeNode := importTypeNode.Argument.AsLiteralTypeNode() - if IsStringLiteral(literalTypeNode.Literal) { - return literalTypeNode.Literal + if IsLiteralTypeNode(importTypeNode.Argument()) { + literalTypeNode := importTypeNode.Argument().AsLiteralTypeNode() + if IsStringLiteral(literalTypeNode.Literal()) { + return literalTypeNode.Literal() } } } @@ -2007,18 +2012,18 @@ func IsExpressionNode(node *Node) bool { return true case KindMetaProperty: // `import.` in `import.(...)` is not an expression - return !IsImportCall(node.Parent) || node.Parent.Expression() != node + return !IsImportCall(node.Parent()) || node.Parent().Expression() != node case KindExpressionWithTypeArguments: - return !IsHeritageClause(node.Parent) + return !IsHeritageClause(node.Parent()) case KindQualifiedName: - for node.Parent.Kind == KindQualifiedName { - node = node.Parent + for node.Parent().Kind == KindQualifiedName { + node = node.Parent() } - return IsTypeQueryNode(node.Parent) || IsJSDocLinkLike(node.Parent) || IsJSDocNameReference(node.Parent) || IsJsxTagName(node) + return IsTypeQueryNode(node.Parent()) || IsJSDocLinkLike(node.Parent()) || IsJSDocNameReference(node.Parent()) || IsJsxTagName(node) case KindPrivateIdentifier: - return IsBinaryExpression(node.Parent) && node.Parent.AsBinaryExpression().Left == node && node.Parent.AsBinaryExpression().OperatorToken.Kind == KindInKeyword + return IsBinaryExpression(node.Parent()) && node.Parent().AsBinaryExpression().Left() == node && node.Parent().AsBinaryExpression().OperatorToken().Kind == KindInKeyword case KindIdentifier: - if IsTypeQueryNode(node.Parent) || IsJSDocLinkLike(node.Parent) || IsJSDocNameReference(node.Parent) || IsJsxTagName(node) { + if IsTypeQueryNode(node.Parent()) || IsJSDocLinkLike(node.Parent()) || IsJSDocNameReference(node.Parent()) || IsJsxTagName(node) { return true } fallthrough @@ -2030,7 +2035,7 @@ func IsExpressionNode(node *Node) bool { } func IsInExpressionContext(node *Node) bool { - parent := node.Parent + parent := node.Parent() switch parent.Kind { case KindVariableDeclaration, KindParameter, KindPropertyDeclaration, KindPropertySignature, KindEnumMember, KindPropertyAssignment, KindBindingElement: return parent.Initializer() == node @@ -2040,16 +2045,16 @@ func IsInExpressionContext(node *Node) bool { return parent.Expression() == node case KindForStatement: s := parent.AsForStatement() - return s.Initializer == node && s.Initializer.Kind != KindVariableDeclarationList || s.Condition == node || s.Incrementor == node + 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 + return s.Initializer() == node && s.Initializer().Kind != KindVariableDeclarationList || s.Expression() == node case KindDecorator, KindJsxExpression, KindJsxSpreadAttribute, KindSpreadAssignment: return true case KindExpressionWithTypeArguments: return parent.Expression() == node && !IsPartOfTypeNode(parent) case KindShorthandPropertyAssignment: - return parent.AsShorthandPropertyAssignment().ObjectAssignmentInitializer == node + return parent.AsShorthandPropertyAssignment().ObjectAssignmentInitializer() == node case KindFunctionExpression, KindClassExpression: // The name of a function or class expression is a declaration name, not an expression. return parent.Name() != node @@ -2069,14 +2074,14 @@ func IsPartOfTypeNode(node *Node) bool { KindNeverKeyword: return true case KindVoidKeyword: - return node.Parent.Kind != KindVoidExpression + return node.Parent().Kind != KindVoidExpression case KindExpressionWithTypeArguments: return isPartOfTypeExpressionWithTypeArguments(node) case KindTypeParameter: - return node.Parent.Kind == KindMappedType || node.Parent.Kind == KindInferType + return node.Parent().Kind == KindMappedType || node.Parent().Kind == KindInferType case KindIdentifier: - parent := node.Parent - if IsQualifiedName(parent) && parent.AsQualifiedName().Right == node { + parent := node.Parent() + if IsQualifiedName(parent) && parent.AsQualifiedName().Right() == node { return isPartOfTypeNodeInParent(parent) } if IsPropertyAccessExpression(parent) && parent.AsPropertyAccessExpression().Name() == node { @@ -2090,7 +2095,7 @@ func IsPartOfTypeNode(node *Node) bool { } func isPartOfTypeNodeInParent(node *Node) bool { - parent := node.Parent + parent := node.Parent() if parent.Kind == KindTypeQuery { return false } @@ -2111,7 +2116,7 @@ func isPartOfTypeNodeInParent(node *Node) bool { case KindExpressionWithTypeArguments: return isPartOfTypeExpressionWithTypeArguments(parent) case KindTypeParameter: - return node == parent.AsTypeParameterDeclaration().Constraint + return node == parent.AsTypeParameterDeclaration().Constraint() case KindVariableDeclaration, KindParameter, KindPropertyDeclaration, KindPropertySignature, KindFunctionDeclaration, KindFunctionExpression, KindArrowFunction, KindConstructor, KindMethodDeclaration, KindMethodSignature, KindGetAccessor, KindSetAccessor, KindCallSignature, KindConstructSignature, KindIndexSignature, @@ -2124,8 +2129,8 @@ func isPartOfTypeNodeInParent(node *Node) bool { } func isPartOfTypeExpressionWithTypeArguments(node *Node) bool { - parent := node.Parent - return IsHeritageClause(parent) && (!IsClassLike(parent.Parent) || parent.AsHeritageClause().Token == KindImplementsKeyword) || + parent := node.Parent() + return IsHeritageClause(parent) && (!IsClassLike(parent.Parent()) || parent.AsHeritageClause().Token == KindImplementsKeyword) || IsJSDocImplementsTag(parent) || IsJSDocAugmentsTag(parent) } @@ -2168,7 +2173,7 @@ func isImportMetaProperty(node *Node, name string) bool { func IsSourcePhaseImport(node *Node) bool { if IsImportDeclaration(node) { - clause := node.AsImportDeclaration().ImportClause + clause := node.AsImportDeclaration().ImportClause() return clause != nil && clause.AsImportClause().PhaseModifier == KindSourceKeyword } return IsSourcePhaseImportCall(node) @@ -2196,11 +2201,11 @@ func EntityNameToString(name *Node, getTextOfNode func(*Node) string) string { } return getTextOfNode(name) case KindQualifiedName: - return EntityNameToString(name.AsQualifiedName().Left, getTextOfNode) + "." + EntityNameToString(name.AsQualifiedName().Right, getTextOfNode) + return EntityNameToString(name.AsQualifiedName().Left(), getTextOfNode) + "." + EntityNameToString(name.AsQualifiedName().Right(), getTextOfNode) case KindPropertyAccessExpression: return EntityNameToString(name.Expression(), getTextOfNode) + "." + EntityNameToString(name.AsPropertyAccessExpression().Name(), getTextOfNode) case KindJsxNamespacedName: - return EntityNameToString(name.AsJsxNamespacedName().Namespace, getTextOfNode) + ":" + EntityNameToString(name.AsJsxNamespacedName().Name(), getTextOfNode) + return EntityNameToString(name.AsJsxNamespacedName().Namespace(), getTextOfNode) + ":" + EntityNameToString(name.AsJsxNamespacedName().Name(), getTextOfNode) } panic("Unhandled case in EntityNameToString") } @@ -2220,7 +2225,7 @@ func TryGetTextOfPropertyName(name *Node) (string, bool) { return name.Expression().Text(), true } case KindJsxNamespacedName: - return name.AsJsxNamespacedName().Namespace.Text() + ":" + name.Name().Text(), true + return name.AsJsxNamespacedName().Namespace().Text() + ":" + name.Name().Text(), true } return "", false } @@ -2249,8 +2254,8 @@ func GetNewTargetContainer(node *Node) *Node { } func GetEnclosingBlockScopeContainer(node *Node) *Node { - return FindAncestor(node.Parent, func(current *Node) bool { - return IsBlockScope(current, current.Parent) + return FindAncestor(node.Parent(), func(current *Node) bool { + return IsBlockScope(current, current.Parent()) }) } @@ -2348,20 +2353,20 @@ func IsLabelOfLabeledStatement(node *Node) bool { if !IsIdentifier(node) { return false } - if !IsLabeledStatement(node.Parent) { + if !IsLabeledStatement(node.Parent()) { return false } - return node == node.Parent.Label() + return node == node.Parent().Label() } func IsJumpStatementTarget(node *Node) bool { if !IsIdentifier(node) { return false } - if !IsBreakOrContinueStatement(node.Parent) { + if !IsBreakOrContinueStatement(node.Parent()) { return false } - return node == node.Parent.Label() + return node == node.Parent().Label() } func IsBreakOrContinueStatement(node *Node) bool { @@ -2384,7 +2389,7 @@ func pushAncestor(ancestors []*Node, parent *Node) []*Node { // Otherwise, we return `nil` and the value of `node.Parent`. func popAncestor(ancestors []*Node, node *Node) ([]*Node, *Node) { if len(ancestors) == 0 { - return nil, node.Parent + return nil, node.Parent() } n := len(ancestors) - 1 return ancestors[:n], ancestors[n] @@ -2405,8 +2410,8 @@ func GetModuleInstanceState(node *Node) ModuleInstanceState { func getModuleInstanceState(node *Node, ancestors []*Node, visited map[NodeId]ModuleInstanceState) ModuleInstanceState { module := node.AsModuleDeclaration() - if module.Body != nil { - return getModuleInstanceStateCached(module.Body, pushAncestor(ancestors, node), visited) + if module.Body() != nil { + return getModuleInstanceStateCached(module.Body(), pushAncestor(ancestors, node), visited) } else { return ModuleInstanceStateInstantiated } @@ -2444,11 +2449,11 @@ func getModuleInstanceStateWorker(node *Node, ancestors []*Node, visited map[Nod } case KindExportDeclaration: decl := node.AsExportDeclaration() - if decl.ModuleSpecifier == nil && decl.ExportClause != nil && decl.ExportClause.Kind == KindNamedExports { + if decl.ModuleSpecifier() == nil && decl.ExportClause() != nil && decl.ExportClause().Kind == KindNamedExports { state := ModuleInstanceStateNonInstantiated ancestors = pushAncestor(ancestors, node) - ancestors = pushAncestor(ancestors, decl.ExportClause) - for _, specifier := range decl.ExportClause.Elements() { + ancestors = pushAncestor(ancestors, decl.ExportClause()) + for _, specifier := range decl.ExportClause().Elements() { specifierState := getModuleInstanceStateForAliasTarget(specifier, ancestors, visited) if specifierState > state { state = specifierState @@ -2532,14 +2537,14 @@ func NodeHasName(statement *Node, id *Node) bool { return IsIdentifier(name) && name.Text() == id.Text() } if IsVariableStatement(statement) { - declarations := statement.AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes + declarations := statement.AsVariableStatement().DeclarationList().AsVariableDeclarationList().Declarations().Nodes return core.Some(declarations, func(d *Node) bool { return NodeHasName(d, id) }) } return false } func IsInternalModuleImportEqualsDeclaration(node *Node) bool { - return IsImportEqualsDeclaration(node) && node.AsImportEqualsDeclaration().ModuleReference.Kind != KindExternalModuleReference + return IsImportEqualsDeclaration(node) && node.AsImportEqualsDeclaration().ModuleReference().Kind != KindExternalModuleReference } func IsConstAssertion(node *Node) bool { @@ -2551,7 +2556,7 @@ func IsConstAssertion(node *Node) bool { } func IsConstTypeReference(node *Node) bool { - return IsTypeReferenceNode(node) && len(node.TypeArguments()) == 0 && IsIdentifier(node.AsTypeReferenceNode().TypeName) && node.AsTypeReferenceNode().TypeName.Text() == "const" + return IsTypeReferenceNode(node) && len(node.TypeArguments()) == 0 && IsIdentifier(node.AsTypeReferenceNode().TypeName()) && node.AsTypeReferenceNode().TypeName().Text() == "const" } func IsGlobalSourceFile(node *Node) bool { @@ -2589,9 +2594,9 @@ func GetFirstIdentifier(node *Node) *Node { case KindIdentifier: return node case KindQualifiedName: - return GetFirstIdentifier(node.AsQualifiedName().Left) + return GetFirstIdentifier(node.AsQualifiedName().Left()) case KindPropertyAccessExpression: - return GetFirstIdentifier(node.AsPropertyAccessExpression().Expression) + return GetFirstIdentifier(node.AsPropertyAccessExpression().Expression()) } panic("Unhandled case in GetFirstIdentifier") } @@ -2600,13 +2605,13 @@ func GetNamespaceDeclarationNode(node *Node) *Node { switch node.Kind { case KindImportDeclaration, KindJSImportDeclaration: importClause := node.ImportClause() - if importClause != nil && importClause.AsImportClause().NamedBindings != nil && IsNamespaceImport(importClause.AsImportClause().NamedBindings) { - return importClause.AsImportClause().NamedBindings + if importClause != nil && importClause.AsImportClause().NamedBindings() != nil && IsNamespaceImport(importClause.AsImportClause().NamedBindings()) { + return importClause.AsImportClause().NamedBindings() } case KindImportEqualsDeclaration: return node case KindExportDeclaration: - exportClause := node.AsExportDeclaration().ExportClause + exportClause := node.AsExportDeclaration().ExportClause() if exportClause != nil && IsNamespaceExport(exportClause) { return exportClause } @@ -2624,7 +2629,7 @@ func IsDefaultImport(node *Node /*ImportDeclaration | ImportEqualsDeclaration | switch node.Kind { case KindImportDeclaration, KindJSImportDeclaration: importClause := node.ImportClause() - return importClause != nil && importClause.AsImportClause().name != nil + return importClause != nil && importClause.AsImportClause().name.get() != nil } return false } @@ -2680,7 +2685,7 @@ func GetDeclarationContainer(node *Node) *Node { default: return true } - }).Parent + }).Parent() } // Indicates that a symbol is an alias that does not merge with a local declaration. @@ -2722,7 +2727,7 @@ func IsAliasSymbolDeclaration(node *Node) bool { case KindBinaryExpression: switch GetAssignmentDeclarationKind(node) { case JSDeclarationKindModuleExports, JSDeclarationKindExportsProperty: - return ExpressionIsAlias(node.AsBinaryExpression().Right) + return ExpressionIsAlias(node.AsBinaryExpression().Right()) } } return false @@ -2811,7 +2816,7 @@ func ForEachDynamicImportOrRequireCall( return true } } else if includeTypeSpaceImports && IsLiteralImportTypeNode(node) { - if cb(node, node.AsImportTypeNode().Argument.AsLiteralTypeNode().Literal) { + if cb(node, node.AsImportTypeNode().Argument().AsLiteralTypeNode().Literal()) { return true } } @@ -2830,18 +2835,18 @@ func IsRequireCall(node *Node, requireStringLiteralLikeArgument bool) bool { return false } call := node.AsCallExpression() - if !IsIdentifier(call.Expression) || call.Expression.Text() != "require" { + if !IsIdentifier(call.Expression()) || call.Expression().Text() != "require" { return false } - if len(call.Arguments.Nodes) != 1 { + if len(call.Arguments().Nodes) != 1 { return false } - return !requireStringLiteralLikeArgument || IsStringLiteralLike(call.Arguments.Nodes[0]) + return !requireStringLiteralLikeArgument || IsStringLiteralLike(call.Arguments().Nodes[0]) } func IsRequireVariableStatement(node *Node) bool { if IsVariableStatement(node) { - if declarations := node.AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes; len(declarations) > 0 { + if declarations := node.AsVariableStatement().DeclarationList().AsVariableDeclarationList().Declarations().Nodes; len(declarations) > 0 { return core.Every(declarations, IsVariableDeclarationInitializedToRequire) } } @@ -2904,7 +2909,7 @@ func GetPragmaArgument(pragma *Pragma, name string) string { // The initializer must be a call to `require` with a string literal or a string literal-like argument. func IsVariableDeclarationInitializedToRequire(node *Node) bool { if node.Kind == KindBindingElement { - node = node.Parent.Parent + node = node.Parent().Parent() } return isVariableDeclarationInitializedWithRequireHelper(node, false /*allowAccessedRequire*/) } @@ -2928,7 +2933,7 @@ func isVariableDeclarationInitializedWithRequireHelper(node *Node, allowAccessed initializer = GetLeftmostAccessExpression(initializer) } - return node.Parent.Parent.ModifierFlags()&ModifierFlagsExport == 0 && + return node.Parent().Parent().ModifierFlags()&ModifierFlagsExport == 0 && node.Type() == nil && IsRequireCall(initializer, true /*requireStringLiteralLikeArgument*/) } @@ -2956,7 +2961,7 @@ func IsModuleExportsAccessExpression(node *Node) bool { } func IsModuleExportsQualifiedName(node *Node) bool { - return IsQualifiedName(node) && IsModuleIdentifier(node.AsQualifiedName().Left) && node.AsQualifiedName().Right.Text() == "exports" + return IsQualifiedName(node) && IsModuleIdentifier(node.AsQualifiedName().Left()) && node.AsQualifiedName().Right().Text() == "exports" } func IsCheckJSEnabledForFile(sourceFile *SourceFile, compilerOptions *core.CompilerOptions) bool { @@ -2980,9 +2985,9 @@ func GetLeftmostAccessExpression(expr *Node) *Node { func IsTypeOnlyImportDeclaration(node *Node) bool { switch node.Kind { case KindImportSpecifier: - return node.IsTypeOnly() || node.Parent.Parent.IsTypeOnly() + return node.IsTypeOnly() || node.Parent().Parent().IsTypeOnly() case KindNamespaceImport: - return node.Parent.IsTypeOnly() + return node.Parent().IsTypeOnly() case KindImportClause, KindImportEqualsDeclaration: return node.IsTypeOnly() } @@ -2992,12 +2997,12 @@ func IsTypeOnlyImportDeclaration(node *Node) bool { func isTypeOnlyExportDeclaration(node *Node) bool { switch node.Kind { case KindExportSpecifier: - return node.IsTypeOnly() || node.Parent.Parent.IsTypeOnly() + return node.IsTypeOnly() || node.Parent().Parent().IsTypeOnly() case KindExportDeclaration: d := node.AsExportDeclaration() - return d.IsTypeOnly && d.ModuleSpecifier != nil && d.ExportClause == nil + return d.IsTypeOnly && d.ModuleSpecifier() != nil && d.ExportClause() == nil case KindNamespaceExport: - return node.Parent.IsTypeOnly() + return node.Parent().IsTypeOnly() } return false } @@ -3032,7 +3037,7 @@ func IsCallLikeExpression(node *Node) bool { KindTaggedTemplateExpression, KindDecorator: return true case KindBinaryExpression: - return node.AsBinaryExpression().OperatorToken.Kind == KindInstanceOfKeyword + return node.AsBinaryExpression().OperatorToken().Kind == KindInstanceOfKeyword } return false } @@ -3064,10 +3069,10 @@ func IsThisInTypeQuery(node *Node) bool { if !IsThisIdentifier(node) { return false } - for IsQualifiedName(node.Parent) && node.Parent.AsQualifiedName().Left == node { - node = node.Parent + for IsQualifiedName(node.Parent()) && node.Parent().AsQualifiedName().Left() == node { + node = node.Parent() } - return node.Parent.Kind == KindTypeQuery + return node.Parent().Kind == KindTypeQuery } // Gets whether a bound `VariableDeclaration` or `VariableDeclarationList` is part of a `let` declaration. @@ -3145,7 +3150,7 @@ func GetTypeAnnotationNode(node *Node) *TypeNode { default: funcLike := node.FunctionLikeData() if funcLike != nil { - return funcLike.Type + return funcLike.Type() } return nil } @@ -3176,7 +3181,7 @@ func IsJSDocSingleCommentNodeList(nodeList *NodeList) bool { if nodeList == nil || len(nodeList.Nodes) == 0 { return false } - parent := nodeList.Nodes[0].Parent + parent := nodeList.Nodes[0].Parent() if parent == nil { return false } @@ -3185,10 +3190,10 @@ func IsJSDocSingleCommentNodeList(nodeList *NodeList) bool { // See `IsJSDocSingleCommentNode`. func IsJSDocSingleCommentNodeComment(node *Node) bool { - if node == nil || node.Parent == nil { + if node == nil || node.Parent() == nil { return false } - return IsJSDocSingleCommentNode(node.Parent) && node == node.Parent.CommentList().Nodes[0] + return IsJSDocSingleCommentNode(node.Parent()) && node == node.Parent().CommentList().Nodes[0] } // In Strada, if a JSDoc node has a single comment, that comment is represented as a string property @@ -3209,28 +3214,28 @@ func isIdentifierInNonEmittingHeritageClause(node *Node) bool { if !IsIdentifier(node) { return false } - parent := node.Parent + parent := node.Parent() for IsPropertyAccessExpression(parent) || IsExpressionWithTypeArguments(parent) { - parent = parent.Parent + parent = parent.Parent() } - return IsHeritageClause(parent) && (parent.AsHeritageClause().Token == KindImplementsKeyword || IsInterfaceDeclaration(parent.Parent)) + return IsHeritageClause(parent) && (parent.AsHeritageClause().Token == KindImplementsKeyword || IsInterfaceDeclaration(parent.Parent())) } func isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node *Node) bool { for NodeKindIs(node, KindIdentifier, KindPropertyAccessExpression) { - node = node.Parent + node = node.Parent() } if node.Kind != KindComputedPropertyName { return false } - if HasSyntacticModifier(node.Parent, ModifierFlagsAbstract) { + if HasSyntacticModifier(node.Parent(), ModifierFlagsAbstract) { return true } - return NodeKindIs(node.Parent.Parent, KindInterfaceDeclaration, KindTypeLiteral) + return NodeKindIs(node.Parent().Parent(), KindInterfaceDeclaration, KindTypeLiteral) } func isShorthandPropertyNameUseSite(useSite *Node) bool { - return IsIdentifier(useSite) && IsShorthandPropertyAssignment(useSite.Parent) && useSite.Parent.AsShorthandPropertyAssignment().Name() == useSite + return IsIdentifier(useSite) && IsShorthandPropertyAssignment(useSite.Parent()) && useSite.Parent().AsShorthandPropertyAssignment().Name() == useSite } func GetPropertyNameForPropertyNameNode(name *Node) string { @@ -3244,7 +3249,7 @@ func GetPropertyNameForPropertyNameNode(name *Node) string { return nameExpression.Text() } if IsSignedNumericLiteral(nameExpression) { - text := nameExpression.AsPrefixUnaryExpression().Operand.Text() + text := nameExpression.AsPrefixUnaryExpression().Operand().Text() if nameExpression.AsPrefixUnaryExpression().Operator == KindMinusToken { text = "-" + text } @@ -3289,11 +3294,11 @@ func HasResolutionModeOverride(node *Node) bool { var attributes *ImportAttributesNode switch node.Kind { case KindImportType: - attributes = node.AsImportTypeNode().Attributes + attributes = node.AsImportTypeNode().Attributes() case KindImportDeclaration, KindJSImportDeclaration: - attributes = node.AsImportDeclaration().Attributes + attributes = node.AsImportDeclaration().Attributes() case KindExportDeclaration: - attributes = node.AsExportDeclaration().Attributes + attributes = node.AsExportDeclaration().Attributes() } if attributes != nil { _, ok := attributes.GetResolutionModeOverride(nil) @@ -3316,7 +3321,7 @@ func IsTemplateLiteralToken(node *Node) bool { func GetExternalModuleImportEqualsDeclarationExpression(node *Node) *Node { debug.Assert(IsExternalModuleImportEqualsDeclaration(node)) - return node.AsImportEqualsDeclaration().ModuleReference.Expression() + return node.AsImportEqualsDeclaration().ModuleReference().Expression() } func CreateModifiersFromModifierFlags(flags ModifierFlags, createModifier func(kind Kind) *Node) []*Node { @@ -3387,15 +3392,15 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL node.AsTypeParameterDeclaration(), modifierArray, node.Name(), - node.AsTypeParameterDeclaration().Constraint, - node.AsTypeParameterDeclaration().Expression, - node.AsTypeParameterDeclaration().DefaultType, + node.AsTypeParameterDeclaration().Constraint(), + node.AsTypeParameterDeclaration().Expression(), + node.AsTypeParameterDeclaration().DefaultType(), ) case KindParameter: return factory.UpdateParameterDeclaration( node.AsParameterDeclaration(), modifierArray, - node.AsParameterDeclaration().DotDotDotToken, + node.AsParameterDeclaration().DotDotDotToken(), node.Name(), node.QuestionToken(), node.Type(), @@ -3441,13 +3446,13 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL return factory.UpdateMethodDeclaration( node.AsMethodDeclaration(), modifierArray, - node.AsMethodDeclaration().AsteriskToken, + node.AsMethodDeclaration().AsteriskToken(), node.Name(), node.PostfixToken(), node.TypeParameterList(), node.ParameterList(), node.Type(), - node.AsMethodDeclaration().FullSignature, + node.AsMethodDeclaration().FullSignature(), node.Body(), ) case KindConstructor: @@ -3457,7 +3462,7 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL node.TypeParameterList(), node.ParameterList(), node.Type(), - node.AsConstructorDeclaration().FullSignature, + node.AsConstructorDeclaration().FullSignature(), node.Body(), ) case KindGetAccessor: @@ -3468,7 +3473,7 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL node.TypeParameterList(), node.ParameterList(), node.Type(), - node.AsGetAccessorDeclaration().FullSignature, + node.AsGetAccessorDeclaration().FullSignature(), node.Body(), ) case KindSetAccessor: @@ -3479,7 +3484,7 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL node.TypeParameterList(), node.ParameterList(), node.Type(), - node.AsSetAccessorDeclaration().FullSignature, + node.AsSetAccessorDeclaration().FullSignature(), node.Body(), ) case KindIndexSignature: @@ -3493,12 +3498,12 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL return factory.UpdateFunctionExpression( node.AsFunctionExpression(), modifierArray, - node.AsFunctionExpression().AsteriskToken, + node.AsFunctionExpression().AsteriskToken(), node.Name(), node.TypeParameterList(), node.ParameterList(), node.Type(), - node.AsFunctionExpression().FullSignature, + node.AsFunctionExpression().FullSignature(), node.Body(), ) case KindArrowFunction: @@ -3508,8 +3513,8 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL node.TypeParameterList(), node.ParameterList(), node.Type(), - node.AsArrowFunction().FullSignature, - node.AsArrowFunction().EqualsGreaterThanToken, + node.AsArrowFunction().FullSignature(), + node.AsArrowFunction().EqualsGreaterThanToken(), node.Body(), ) case KindClassExpression: @@ -3518,25 +3523,25 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL modifierArray, node.Name(), node.TypeParameterList(), - node.AsClassExpression().HeritageClauses, + node.AsClassExpression().HeritageClauses(), node.MemberList(), ) case KindVariableStatement: return factory.UpdateVariableStatement( node.AsVariableStatement(), modifierArray, - node.AsVariableStatement().DeclarationList, + node.AsVariableStatement().DeclarationList(), ) case KindFunctionDeclaration: return factory.UpdateFunctionDeclaration( node.AsFunctionDeclaration(), modifierArray, - node.AsFunctionDeclaration().AsteriskToken, + node.AsFunctionDeclaration().AsteriskToken(), node.Name(), node.TypeParameterList(), node.ParameterList(), node.Type(), - node.AsFunctionDeclaration().FullSignature, + node.AsFunctionDeclaration().FullSignature(), node.Body(), ) case KindClassDeclaration: @@ -3545,7 +3550,7 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL modifierArray, node.Name(), node.TypeParameterList(), - node.AsClassDeclaration().HeritageClauses, + node.AsClassDeclaration().HeritageClauses(), node.MemberList(), ) case KindInterfaceDeclaration: @@ -3554,7 +3559,7 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL modifierArray, node.Name(), node.TypeParameterList(), - node.AsInterfaceDeclaration().HeritageClauses, + node.AsInterfaceDeclaration().HeritageClauses(), node.MemberList(), ) case KindTypeAliasDeclaration: @@ -3587,7 +3592,7 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL modifierArray, node.IsTypeOnly(), node.Name(), - node.AsImportEqualsDeclaration().ModuleReference, + node.AsImportEqualsDeclaration().ModuleReference(), ) case KindImportDeclaration: return factory.UpdateImportDeclaration( @@ -3595,7 +3600,7 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL modifierArray, node.ImportClause(), node.ModuleSpecifier(), - node.AsImportDeclaration().Attributes, + node.AsImportDeclaration().Attributes(), ) case KindExportAssignment: return factory.UpdateExportAssignment( @@ -3610,9 +3615,9 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL node.AsExportDeclaration(), modifierArray, node.IsTypeOnly(), - node.AsExportDeclaration().ExportClause, + node.AsExportDeclaration().ExportClause(), node.ModuleSpecifier(), - node.AsExportDeclaration().Attributes, + node.AsExportDeclaration().Attributes(), ) } panic(fmt.Sprintf("Node that does not have modifiers tried to have modifier replaced: %d", node.Kind)) @@ -3662,7 +3667,7 @@ func IsTypeDeclaration(node *Node) bool { case KindImportClause: return node.IsTypeOnly() && node.AsImportClause().Name() != nil case KindImportSpecifier, KindExportSpecifier: - return node.Parent.Parent.IsTypeOnly() + return node.Parent().Parent().IsTypeOnly() default: return false } @@ -3670,28 +3675,28 @@ func IsTypeDeclaration(node *Node) bool { func IsTypeDeclarationName(name *Node) bool { return name.Kind == KindIdentifier && - IsTypeDeclaration(name.Parent) && - GetNameOfDeclaration(name.Parent) == name + IsTypeDeclaration(name.Parent()) && + GetNameOfDeclaration(name.Parent()) == name } func IsRightSideOfPropertyAccess(node *Node) bool { - return node.Parent.Kind == KindPropertyAccessExpression && node.Parent.Name() == node + return node.Parent().Kind == KindPropertyAccessExpression && node.Parent().Name() == node } func IsArgumentExpressionOfElementAccess(node *Node) bool { - return node.Parent != nil && node.Parent.Kind == KindElementAccessExpression && node.Parent.AsElementAccessExpression().ArgumentExpression == node + return node.Parent() != nil && node.Parent().Kind == KindElementAccessExpression && node.Parent().AsElementAccessExpression().ArgumentExpression() == node } func ClimbPastPropertyAccess(node *Node) *Node { if IsRightSideOfPropertyAccess(node) { - return node.Parent + return node.Parent() } return node } func climbPastPropertyOrElementAccess(node *Node) *Node { if IsRightSideOfPropertyAccess(node) || IsArgumentExpressionOfElementAccess(node) { - return node.Parent + return node.Parent() } return node } @@ -3705,7 +3710,7 @@ func selectExpressionOfCallOrNewExpressionOrDecorator(node *Node) *Node { func selectTagOfTaggedTemplateExpression(node *Node) *Node { if IsTaggedTemplateExpression(node) { - return node.AsTaggedTemplateExpression().Tag + return node.AsTaggedTemplateExpression().Tag() } return nil } @@ -3760,14 +3765,14 @@ func isCalleeWorker( target = SkipOuterExpressions(target, OEKAll) } } - return target != nil && target.Parent != nil && pred(target.Parent) && calleeSelector(target.Parent) == target + return target != nil && target.Parent() != nil && pred(target.Parent()) && calleeSelector(target.Parent()) == target } func IsRightSideOfQualifiedNameOrPropertyAccess(node *Node) bool { - parent := node.Parent + parent := node.Parent() switch parent.Kind { case KindQualifiedName: - return parent.AsQualifiedName().Right == node + return parent.AsQualifiedName().Right() == node case KindPropertyAccessExpression: return parent.AsPropertyAccessExpression().Name() == node case KindMetaProperty: @@ -3795,11 +3800,11 @@ func IsJsxOpeningLikeElement(node *Node) bool { func GetInvokedExpression(node *Node) *Node { switch node.Kind { case KindTaggedTemplateExpression: - return node.AsTaggedTemplateExpression().Tag + return node.AsTaggedTemplateExpression().Tag() case KindJsxOpeningElement, KindJsxSelfClosingElement: return node.TagName() case KindBinaryExpression: - return node.AsBinaryExpression().Right + return node.AsBinaryExpression().Right() case KindJsxOpeningFragment: return node default: @@ -3973,7 +3978,7 @@ func GetTargetOfBindingOrAssignmentElement(bindingElement *Node) *Node { // `[a]` in `[[a] = 1] = ...` // `a.b` in `[a.b = 1] = ...` // `a[0]` in `[a[0] = 1] = ...` - return GetTargetOfBindingOrAssignmentElement(bindingElement.AsBinaryExpression().Left) + return GetTargetOfBindingOrAssignmentElement(bindingElement.AsBinaryExpression().Left()) } if IsSpreadElement(bindingElement) { @@ -4077,9 +4082,9 @@ func IsEmptyArrayLiteral(expression *Node) bool { func GetRestIndicatorOfBindingOrAssignmentElement(bindingElement *Node) *Node { switch bindingElement.Kind { case KindParameter: - return bindingElement.AsParameterDeclaration().DotDotDotToken + return bindingElement.AsParameterDeclaration().DotDotDotToken() case KindBindingElement: - return bindingElement.AsBindingElement().DotDotDotToken + return bindingElement.AsBindingElement().DotDotDotToken() case KindSpreadElement, KindSpreadAssignment: return bindingElement } @@ -4094,7 +4099,7 @@ func IsJSDocNameReferenceContext(node *Node) bool { // GetJSDocRoot returns the containing JSDoc node for a node inside a JSDoc comment. func GetJSDocRoot(node *Node) *Node { - return FindAncestor(node.Parent, func(n *Node) bool { + return FindAncestor(node.Parent(), func(n *Node) bool { return n.Kind == KindJSDoc }) } @@ -4105,7 +4110,7 @@ func GetJSDocHost(node *Node) *Node { if jsDoc == nil { return nil } - return jsDoc.Parent + return jsDoc.Parent() } // GetHostSignatureFromJSDoc returns the function-like declaration that hosts the JSDoc comment @@ -4129,13 +4134,13 @@ func GetHostSignatureFromJSDoc(node *Node) *Node { // Keep these hosts aligned with JSDoc parameter reparsing so unmatched @param diagnostics use the same attachment rules. // Keep in sync with getNextJSDocCommentLocation in the API's src/ast/jsdoc.ts func GetNextJSDocCommentLocation(node *Node) *Node { - if parent := node.Parent; parent != nil { + if parent := node.Parent(); parent != nil { switch parent.Kind { case KindPropertyAssignment, KindExportAssignment, KindPropertyDeclaration, KindVariableDeclaration, KindSatisfiesExpression, KindReturnStatement, KindVariableStatement, KindExpressionStatement: return parent case KindVariableDeclarationList: - if parent.AsVariableDeclarationList().Declarations.Nodes[0] == node { + if parent.AsVariableDeclarationList().Declarations().Nodes[0] == node { return parent } } @@ -4159,10 +4164,10 @@ func IsPrimitiveLiteralValue(node *Node, includeBigInt bool) bool { return includeBigInt case KindPrefixUnaryExpression: if node.AsPrefixUnaryExpression().Operator == KindMinusToken { - return IsNumericLiteral(node.AsPrefixUnaryExpression().Operand) || (includeBigInt && IsBigIntLiteral(node.AsPrefixUnaryExpression().Operand)) + return IsNumericLiteral(node.AsPrefixUnaryExpression().Operand()) || (includeBigInt && IsBigIntLiteral(node.AsPrefixUnaryExpression().Operand())) } if node.AsPrefixUnaryExpression().Operator == KindPlusToken { - return IsNumericLiteral(node.AsPrefixUnaryExpression().Operand) + return IsNumericLiteral(node.AsPrefixUnaryExpression().Operand()) } return false default: @@ -4220,34 +4225,34 @@ func IsExpandoInitializer(declaration *Node, initializer *Node) bool { } func GetContainingFunction(node *Node) *Node { - return FindAncestor(node.Parent, IsFunctionLike) + return FindAncestor(node.Parent(), IsFunctionLike) } func ImportFromModuleSpecifier(node *Node) *Node { if result := TryGetImportFromModuleSpecifier(node); result != nil { return result } - debug.FailBadSyntaxKind(node.Parent) + debug.FailBadSyntaxKind(node.Parent()) return nil } func TryGetImportFromModuleSpecifier(node *StringLiteralLike) *Node { - switch node.Parent.Kind { + switch node.Parent().Kind { case KindImportDeclaration, KindJSImportDeclaration, KindExportDeclaration: - return node.Parent + return node.Parent() case KindExternalModuleReference: - return node.Parent.Parent + return node.Parent().Parent() case KindCallExpression: - if IsImportCall(node.Parent) || IsRequireCall(node.Parent, false /*requireStringLiteralLikeArgument*/) { - return node.Parent + if IsImportCall(node.Parent()) || IsRequireCall(node.Parent(), false /*requireStringLiteralLikeArgument*/) { + return node.Parent() } return nil case KindLiteralType: if !IsStringLiteral(node) { return nil } - if IsImportTypeNode(node.Parent.Parent) { - return node.Parent.Parent + if IsImportTypeNode(node.Parent().Parent()) { + return node.Parent().Parent() } return nil } @@ -4255,7 +4260,7 @@ func TryGetImportFromModuleSpecifier(node *StringLiteralLike) *Node { } func IsImplicitlyExportedJSDocDeclaration(node *Node) bool { - if !IsSourceFile(node.Parent) || !IsExternalOrCommonJSModule(node.Parent.AsSourceFile()) { + if !IsSourceFile(node.Parent()) || !IsExternalOrCommonJSModule(node.Parent().AsSourceFile()) { return false } if IsJSTypeAliasDeclaration(node) { @@ -4302,11 +4307,11 @@ func GetFirstConstructorWithBody(node *Node) *Node { func IsPotentiallyExecutableNode(node *Node) bool { if KindFirstStatement <= node.Kind && node.Kind <= KindLastStatement { if IsVariableStatement(node) { - declarationList := node.AsVariableStatement().DeclarationList + declarationList := node.AsVariableStatement().DeclarationList() if GetCombinedNodeFlags(declarationList)&NodeFlagsBlockScoped != 0 { return true } - declarations := declarationList.AsVariableDeclarationList().Declarations.Nodes + declarations := declarationList.AsVariableDeclarationList().Declarations().Nodes return core.Some(declarations, func(d *Node) bool { return d.Initializer() != nil }) @@ -4380,7 +4385,7 @@ func ClassElementOrClassElementParameterIsDecorated(useLegacyDecorators bool, no return false } if decls.SetAccessor != nil { - parameters = decls.SetAccessor.Parameters + parameters = decls.SetAccessor.Parameters() } } else if IsMethodDeclaration(node) { parameters = node.ParameterList() @@ -4508,7 +4513,7 @@ func IsAsyncFunction(node *Node) bool { switch node.Kind { case KindFunctionDeclaration, KindFunctionExpression, KindArrowFunction, KindMethodDeclaration: data := node.BodyData() - return data.Body != nil && data.AsteriskToken == nil && HasSyntacticModifier(node, ModifierFlagsAsync) + return data.Body() != nil && data.AsteriskToken() == nil && HasSyntacticModifier(node, ModifierFlagsAsync) } return false } @@ -4526,10 +4531,10 @@ func GetRestParameterElementType(node *ParameterDeclarationNode) *Node { return node } if node.Kind == KindArrayType { - return node.AsArrayTypeNode().ElementType + return node.AsArrayTypeNode().ElementType() } - if node.Kind == KindTypeReference && node.AsTypeReferenceNode().TypeArguments != nil { - return core.FirstOrNil(node.AsTypeReferenceNode().TypeArguments.Nodes) + if node.Kind == KindTypeReference && node.AsTypeReferenceNode().TypeArguments() != nil { + return core.FirstOrNil(node.AsTypeReferenceNode().TypeArguments().Nodes) } return nil } @@ -4544,7 +4549,7 @@ func TagNamesAreEquivalent(lhs *Expression, rhs *Expression) bool { case KindThisKeyword: return true case KindJsxNamespacedName: - return lhs.AsJsxNamespacedName().Namespace.Text() == rhs.AsJsxNamespacedName().Namespace.Text() && + return lhs.AsJsxNamespacedName().Namespace().Text() == rhs.AsJsxNamespacedName().Namespace().Text() && lhs.AsJsxNamespacedName().Name().Text() == rhs.AsJsxNamespacedName().Name().Text() case KindPropertyAccessExpression: return lhs.AsPropertyAccessExpression().Name().Text() == rhs.AsPropertyAccessExpression().Name().Text() && @@ -4554,7 +4559,7 @@ func TagNamesAreEquivalent(lhs *Expression, rhs *Expression) bool { } func IsTagName(node *Node) bool { - return node.Parent != nil && IsJSDocTag(node.Parent) && node.Parent.TagName() == node + return node.Parent() != nil && IsJSDocTag(node.Parent()) && node.Parent().TagName() == node } // We want to store any numbers/strings if they were a name that could be @@ -4563,15 +4568,15 @@ func IsTagName(node *Node) bool { // "a['propname']" then we want to store "propname" in the name table. func literalIsName(node *Node) bool { return IsDeclarationName(node) || - node.Parent.Kind == KindExternalModuleReference || + node.Parent().Kind == KindExternalModuleReference || isArgumentOfElementAccessExpression(node) || IsLiteralComputedPropertyDeclarationName(node) } func isArgumentOfElementAccessExpression(node *Node) bool { - return node != nil && node.Parent != nil && - node.Parent.Kind == KindElementAccessExpression && - node.Parent.AsElementAccessExpression().ArgumentExpression == node + return node != nil && node.Parent() != nil && + node.Parent().Kind == KindElementAccessExpression && + node.Parent().AsElementAccessExpression().ArgumentExpression() == node } // If the given node is part of a subtree of JSDoc nodes that have been cloned into a reparsed construct, @@ -4628,19 +4633,19 @@ func IsNamedEvaluationSource(node *Node) bool { case KindPropertyAssignment: return !IsProtoSetter(node.AsPropertyAssignment().Name()) case KindShorthandPropertyAssignment: - return node.AsShorthandPropertyAssignment().ObjectAssignmentInitializer != nil + return node.AsShorthandPropertyAssignment().ObjectAssignmentInitializer() != nil case KindVariableDeclaration: return IsIdentifier(node.AsVariableDeclaration().Name()) && node.Initializer() != nil case KindParameter: - return IsIdentifier(node.AsParameterDeclaration().Name()) && node.Initializer() != nil && node.AsParameterDeclaration().DotDotDotToken == nil + return IsIdentifier(node.AsParameterDeclaration().Name()) && node.Initializer() != nil && node.AsParameterDeclaration().DotDotDotToken() == nil case KindBindingElement: - return IsIdentifier(node.AsBindingElement().Name()) && node.Initializer() != nil && node.AsBindingElement().DotDotDotToken == nil + return IsIdentifier(node.AsBindingElement().Name()) && node.Initializer() != nil && node.AsBindingElement().DotDotDotToken() == nil case KindPropertyDeclaration: return node.Initializer() != nil case KindBinaryExpression: - switch node.AsBinaryExpression().OperatorToken.Kind { + switch node.AsBinaryExpression().OperatorToken().Kind { case KindEqualsToken, KindAmpersandAmpersandEqualsToken, KindBarBarEqualsToken, KindQuestionQuestionEqualsToken: - return IsIdentifier(node.AsBinaryExpression().Left) + return IsIdentifier(node.AsBinaryExpression().Left()) } case KindExportAssignment: return true @@ -4658,5 +4663,5 @@ func IsProtoSetter(node *Node) bool { func IsStringLiteralLikeType(node *Node) bool { return node.Kind == KindLiteralType && - IsStringLiteralLike(node.AsLiteralTypeNode().Literal) + IsStringLiteralLike(node.AsLiteralTypeNode().Literal()) } diff --git a/tsc/internal/binder/binder.go b/tsc/internal/binder/binder.go index adf0b17af211f..fc888abffe41e 100644 --- a/tsc/internal/binder/binder.go +++ b/tsc/internal/binder/binder.go @@ -10,6 +10,7 @@ import ( "github.com/microsoft/TypeScript/tsc/internal/core" "github.com/microsoft/TypeScript/tsc/internal/debug" "github.com/microsoft/TypeScript/tsc/internal/diagnostics" + "github.com/microsoft/TypeScript/tsc/internal/linkarena" "github.com/microsoft/TypeScript/tsc/internal/scanner" ) @@ -121,10 +122,16 @@ func bindSourceFile(file *ast.SourceFile) { b := getBinder() defer putBinder(b) b.file = file + // The garbage collector does not look inside nodes, so it does not see the symbols and + // flow nodes they point to. The arena of the file's nodes keeps them alive instead. + arena := file.Arena() + b.symbolArena.OnGrow = func(block []ast.Symbol) { linkarena.KeepSlice(arena, block) } + b.flowNodeArena.OnGrow = func(block []ast.FlowNode) { linkarena.KeepSlice(arena, block) } b.unreachableFlow = b.newFlowNode(ast.FlowFlagsUnreachable) b.bind(file.AsNode()) b.bindDeferredExpandoAssignments() file.SymbolCount = b.symbolCount + file.VerifyArena() }) } @@ -309,7 +316,7 @@ func (b *Binder) getDeclarationName(node *ast.Node) string { return ast.InternalSymbolNameGlobal } if pattern := core.TryParsePattern(moduleName); pattern.IsValid() && pattern.StarIndex >= 0 { - if attributes := node.AsModuleDeclaration().Attributes; attributes != nil { + if attributes := node.AsModuleDeclaration().Attributes(); attributes != nil { return ast.InternalSymbolNamePrefix + "\"" + moduleName + "\"pattern@" + strconv.FormatUint(uint64(ast.GetNodeId(attributes)), 10) } } @@ -335,7 +342,7 @@ func (b *Binder) getDeclarationName(node *ast.Node) string { } if ast.IsSignedNumericLiteral(nameExpression) { unaryExpression := nameExpression.AsPrefixUnaryExpression() - return scanner.TokenToString(unaryExpression.Operator) + unaryExpression.Operand.Text() + return scanner.TokenToString(unaryExpression.Operator) + unaryExpression.Operand().Text() } panic("Only computed properties with literal names have declaration names") } @@ -485,7 +492,7 @@ func (b *Binder) createFlowCondition(flags ast.FlowFlags, antecedent *ast.FlowNo } return b.unreachableFlow } - if (expression.Kind == ast.KindTrueKeyword && flags&ast.FlowFlagsFalseCondition != 0 || expression.Kind == ast.KindFalseKeyword && flags&ast.FlowFlagsTrueCondition != 0) && !ast.IsExpressionOfOptionalChainRoot(expression) && !ast.IsNullishCoalesce(expression.Parent) { + if (expression.Kind == ast.KindTrueKeyword && flags&ast.FlowFlagsFalseCondition != 0 || expression.Kind == ast.KindFalseKeyword && flags&ast.FlowFlagsTrueCondition != 0) && !ast.IsExpressionOfOptionalChainRoot(expression) && !ast.IsNullishCoalesce(expression.Parent()) { return b.unreachableFlow } if !isNarrowingExpression(expression) { @@ -785,7 +792,7 @@ func (b *Binder) bindModuleDeclaration(node *ast.Node) { symbol := b.declareSymbolAndAddToSymbolTable(node, ast.SymbolFlagsValueModule, ast.SymbolFlagsValueModuleExcludes) if ast.IsStringLiteral(name) { - attributes := node.AsModuleDeclaration().Attributes + attributes := node.AsModuleDeclaration().Attributes() pattern := core.TryParsePattern(name.Text()) if !pattern.IsValid() { // An invalid pattern - must have multiple wildcards. @@ -829,11 +836,11 @@ func (b *Binder) bindNamespaceExportDeclaration(node *ast.Node) { b.errorOnNode(node, diagnostics.Modifiers_cannot_appear_here) } switch { - case !ast.IsSourceFile(node.Parent): + case !ast.IsSourceFile(node.Parent()): b.errorOnNode(node, diagnostics.Global_module_exports_may_only_appear_at_top_level) - case !ast.IsExternalModule(node.Parent.AsSourceFile()): + case !ast.IsExternalModule(node.Parent().AsSourceFile()): b.errorOnNode(node, diagnostics.Global_module_exports_may_only_appear_in_module_files) - case !node.Parent.AsSourceFile().IsDeclarationFile: + case !node.Parent().AsSourceFile().IsDeclarationFile: b.errorOnNode(node, diagnostics.Global_module_exports_may_only_appear_in_declaration_files) default: b.declareSymbol(ast.GetSymbolTable(&b.file.GlobalExports), b.file.Symbol, node, ast.SymbolFlagsAlias, ast.SymbolFlagsAliasExcludes) @@ -851,11 +858,11 @@ func (b *Binder) bindExportDeclaration(node *ast.Node) { if b.container.Symbol() == nil { // Export * in some sort of block construct b.bindAnonymousDeclaration(node, ast.SymbolFlagsExportStar, b.getDeclarationName(node)) - } else if decl.ExportClause == nil { + } else if decl.ExportClause() == nil { // All export * declarations are collected in an __export symbol b.declareSymbol(ast.GetExports(b.container.Symbol()), b.container.Symbol(), node, ast.SymbolFlagsExportStar, ast.SymbolFlagsNone) - } else if ast.IsNamespaceExport(decl.ExportClause) { - b.declareSymbol(ast.GetExports(b.container.Symbol()), b.container.Symbol(), decl.ExportClause, ast.SymbolFlagsAlias, ast.SymbolFlagsAliasExcludes) + } else if ast.IsNamespaceExport(decl.ExportClause()) { + b.declareSymbol(ast.GetExports(b.container.Symbol()), b.container.Symbol(), decl.ExportClause(), ast.SymbolFlagsAlias, ast.SymbolFlagsAliasExcludes) } } @@ -1017,7 +1024,7 @@ func (b *Binder) addLateBoundAssignmentDeclarationToSymbol(node *ast.Node, symbo func (b *Binder) bindModuleExportsAssignment(node *ast.Node) { if b.setCommonJSModuleIndicator(node) { container := b.file.AsNode() - flags := core.IfElse(ast.ExpressionIsAlias(node.AsBinaryExpression().Right), ast.SymbolFlagsAlias, ast.SymbolFlagsProperty) + flags := core.IfElse(ast.ExpressionIsAlias(node.AsBinaryExpression().Right()), ast.SymbolFlagsAlias, ast.SymbolFlagsProperty) symbol := b.declareSymbol(ast.GetExports(container.Symbol()), container.Symbol(), node, flags, 0) SetValueDeclaration(symbol, node) } @@ -1077,7 +1084,7 @@ func (b *Binder) bindDeferredExpandoAssignment(node *ast.Node) { func getParentOfPropertyAssignment(node *ast.Node) *ast.Node { switch node.Kind { case ast.KindBinaryExpression: - return node.AsBinaryExpression().Left.Expression() + return node.AsBinaryExpression().Left().Expression() case ast.KindCallExpression: return node.Arguments()[0] } @@ -1087,7 +1094,7 @@ func getParentOfPropertyAssignment(node *ast.Node) *ast.Node { func (b *Binder) bindExportsOrObjectDefineProperty(node *ast.Node) { if b.setCommonJSModuleIndicator(node) { container := b.file.AsNode() - flags := core.IfElse(ast.IsBinaryExpression(node) && ast.ExpressionIsAlias(node.AsBinaryExpression().Right), ast.SymbolFlagsAlias, ast.SymbolFlagsFunctionScopedVariable) + flags := core.IfElse(ast.IsBinaryExpression(node) && ast.ExpressionIsAlias(node.AsBinaryExpression().Right()), ast.SymbolFlagsAlias, ast.SymbolFlagsFunctionScopedVariable) b.declareSymbol(ast.GetExports(container.Symbol()), container.Symbol(), node, flags, ast.SymbolFlagsFunctionScopedVariableExcludes) } } @@ -1105,13 +1112,13 @@ func getInitializerSymbol(symbol *ast.Symbol) *ast.Symbol { case ast.IsFunctionDeclaration(declaration) || ast.IsInJSFile(declaration) && ast.IsClassDeclaration(declaration): return symbol case ast.IsVariableDeclaration(declaration) && - (declaration.Parent.Flags&ast.NodeFlagsConst != 0 || ast.IsInJSFile(declaration)): + (declaration.Parent().Flags&ast.NodeFlagsConst != 0 || ast.IsInJSFile(declaration)): initializer := declaration.Initializer() if ast.IsExpandoInitializer(declaration, initializer) { return initializer.Symbol() } case ast.IsBinaryExpression(declaration) && ast.IsInJSFile(declaration): - initializer := declaration.AsBinaryExpression().Right + initializer := declaration.AsBinaryExpression().Right() if ast.IsExpandoInitializer(declaration, initializer) { return initializer.Symbol() } @@ -1124,7 +1131,7 @@ func (b *Binder) bindThisPropertyAssignment(node *ast.Node) { return } bin := node.AsBinaryExpression() - if ast.IsPropertyAccessExpression(bin.Left) && ast.IsPrivateIdentifier(bin.Left.AsPropertyAccessExpression().Name()) || + if ast.IsPropertyAccessExpression(bin.Left()) && ast.IsPrivateIdentifier(bin.Left().AsPropertyAccessExpression().Name()) || b.thisContainer == nil { return } @@ -1150,7 +1157,7 @@ func (b *Binder) getThisClassAndSymbolTable() (classSymbol *ast.Symbol, symbolTa // !!! constructor functions case ast.KindConstructor, ast.KindPropertyDeclaration, ast.KindMethodDeclaration, ast.KindGetAccessor, ast.KindSetAccessor, ast.KindClassStaticBlockDeclaration: // this.property assignment in class member -- bind to the containing class - classSymbol = b.thisContainer.Parent.Symbol() + classSymbol = b.thisContainer.Parent().Symbol() if ast.IsStatic(b.thisContainer) { symbolTable = ast.GetExports(classSymbol) } else { @@ -1201,16 +1208,16 @@ func (b *Binder) bindParameter(node *ast.Node) { b.checkStrictModeEvalOrArguments(node, decl.Name()) } if ast.IsBindingPattern(decl.Name()) { - index := slices.Index(node.Parent.Parameters(), node) + index := slices.Index(node.Parent().Parameters(), node) b.bindAnonymousDeclaration(node, ast.SymbolFlagsFunctionScopedVariable, "__"+strconv.Itoa(index)) } else { b.declareSymbolAndAddToSymbolTable(node, ast.SymbolFlagsFunctionScopedVariable, ast.SymbolFlagsParameterExcludes) } // If this is a property-parameter, then also declare the property symbol into the // containing class. - if ast.IsParameterPropertyDeclaration(node, node.Parent) { - classDeclaration := node.Parent.Parent - flags := ast.SymbolFlagsProperty | core.IfElse(decl.QuestionToken != nil, ast.SymbolFlagsOptional, ast.SymbolFlagsNone) + if ast.IsParameterPropertyDeclaration(node, node.Parent()) { + classDeclaration := node.Parent().Parent() + flags := ast.SymbolFlagsProperty | core.IfElse(decl.QuestionToken() != nil, ast.SymbolFlagsOptional, ast.SymbolFlagsNone) b.declareSymbol(ast.GetMembers(classDeclaration.Symbol()), classDeclaration.Symbol(), node, flags, ast.SymbolFlagsPropertyExcludes) } } @@ -1225,11 +1232,11 @@ func (b *Binder) bindFunctionDeclaration(node *ast.Node) { func (b *Binder) getInferTypeContainer(node *ast.Node) *ast.Node { extendsType := ast.FindAncestor(node, func(n *ast.Node) bool { - parent := n.Parent - return parent != nil && ast.IsConditionalTypeNode(parent) && parent.AsConditionalTypeNode().ExtendsType == n + parent := n.Parent() + return parent != nil && ast.IsConditionalTypeNode(parent) && parent.AsConditionalTypeNode().ExtendsType() == n }) if extendsType != nil { - return extendsType.Parent + return extendsType.Parent() } return nil } @@ -1258,8 +1265,8 @@ func (b *Binder) bindBlockScopedDeclaration(node *ast.Node, symbolFlags ast.Symb } func (b *Binder) bindTypeParameter(node *ast.Node) { - if node.Parent.Kind == ast.KindInferType { - container := b.getInferTypeContainer(node.Parent) + if node.Parent().Kind == ast.KindInferType { + container := b.getInferTypeContainer(node.Parent()) if container != nil { b.declareSymbol(ast.GetLocals(container), nil /*parent*/, node, ast.SymbolFlagsTypeParameter, ast.SymbolFlagsTypeParameterExcludes) } else { @@ -1390,10 +1397,10 @@ func (b *Binder) getStrictModeBlockScopeFunctionDeclarationMessage(node *ast.Nod func (b *Binder) checkStrictModeBinaryExpression(node *ast.Node) { expr := node.AsBinaryExpression() - if ast.IsLeftHandSideExpression(expr.Left) && ast.IsAssignmentOperator(expr.OperatorToken.Kind) { + if ast.IsLeftHandSideExpression(expr.Left()) && ast.IsAssignmentOperator(expr.OperatorToken().Kind) { // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an // Assignment operator(11.13) or of a PostfixExpression(11.3) - b.checkStrictModeEvalOrArguments(node, expr.Left) + b.checkStrictModeEvalOrArguments(node, expr.Left()) } } @@ -1401,18 +1408,18 @@ func (b *Binder) checkStrictModeCatchClause(node *ast.Node) { // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the // Catch production is eval or arguments clause := node.AsCatchClause() - if clause.VariableDeclaration != nil { - b.checkStrictModeEvalOrArguments(node, clause.VariableDeclaration.AsVariableDeclaration().Name()) + if clause.VariableDeclaration() != nil { + b.checkStrictModeEvalOrArguments(node, clause.VariableDeclaration().AsVariableDeclaration().Name()) } } func (b *Binder) checkStrictModeDeleteExpression(node *ast.Node) { // Grammar checking expr := node.AsDeleteExpression() - if expr.Expression.Kind == ast.KindIdentifier { + if expr.Expression().Kind == ast.KindIdentifier { // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its // UnaryExpression is a direct reference to a variable, function argument, or function name - b.errorOnNode(expr.Expression, diagnostics.X_delete_cannot_be_called_on_an_identifier_in_strict_mode) + b.errorOnNode(expr.Expression(), diagnostics.X_delete_cannot_be_called_on_an_identifier_in_strict_mode) } } @@ -1421,14 +1428,14 @@ func (b *Binder) checkStrictModePostfixUnaryExpression(node *ast.Node) { // The identifier eval or arguments may not appear as the LeftHandSideExpression of an // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator. - b.checkStrictModeEvalOrArguments(node, node.AsPostfixUnaryExpression().Operand) + b.checkStrictModeEvalOrArguments(node, node.AsPostfixUnaryExpression().Operand()) } func (b *Binder) checkStrictModePrefixUnaryExpression(node *ast.Node) { // Grammar checking expr := node.AsPrefixUnaryExpression() if expr.Operator == ast.KindPlusPlusToken || expr.Operator == ast.KindMinusMinusToken { - b.checkStrictModeEvalOrArguments(node, expr.Operand) + b.checkStrictModeEvalOrArguments(node, expr.Operand()) } } @@ -1440,8 +1447,8 @@ func (b *Binder) checkStrictModeWithStatement(node *ast.Node) { func (b *Binder) checkStrictModeLabeledStatement(node *ast.Node) { // Grammar checking for labeledStatement data := node.AsLabeledStatement() - if ast.IsDeclarationStatement(data.Statement) || ast.IsVariableStatement(data.Statement) { - b.errorOnFirstToken(data.Label, diagnostics.A_label_is_not_allowed_here) + if ast.IsDeclarationStatement(data.Statement()) || ast.IsVariableStatement(data.Statement()) { + b.errorOnFirstToken(data.Label(), diagnostics.A_label_is_not_allowed_here) } } @@ -1554,7 +1561,7 @@ func (b *Binder) bindContainer(node *ast.Node, containerFlags ContainerFlags) { node.Flags &^= ast.NodeFlagsReachabilityAndEmitFlags | ast.NodeFlagsContainsThis if b.currentFlow.Flags&ast.FlowFlagsUnreachable == 0 && containerFlags&ContainerFlagsIsFunctionLike != 0 { bodyData := node.BodyData() - if bodyData != nil && ast.NodeIsPresent(bodyData.Body) { + if bodyData != nil && ast.NodeIsPresent(bodyData.Body()) { node.Flags |= ast.NodeFlagsHasImplicitReturn if b.hasExplicitReturn { node.Flags |= ast.NodeFlagsHasExplicitReturn @@ -1778,10 +1785,10 @@ func (b *Binder) bindEachStatementFunctionsFirst(statements *ast.NodeList) { func (b *Binder) setContinueTarget(node *ast.Node, target *ast.FlowLabel) *ast.FlowLabel { label := b.activeLabelList - for label != nil && node.Parent.Kind == ast.KindLabeledStatement { + for label != nil && node.Parent().Kind == ast.KindLabeledStatement { label.continueTarget = target label = label.next - node = node.Parent + node = node.Parent() } return target } @@ -1847,8 +1854,8 @@ func (b *Binder) bindAssignmentTargetFlow(node *ast.Node) { } func (b *Binder) bindDestructuringTargetFlow(node *ast.Node) { - if ast.IsBinaryExpression(node) && node.AsBinaryExpression().OperatorToken.Kind == ast.KindEqualsToken { - b.bindAssignmentTargetFlow(node.AsBinaryExpression().Left) + if ast.IsBinaryExpression(node) && node.AsBinaryExpression().OperatorToken().Kind == ast.KindEqualsToken { + b.bindAssignmentTargetFlow(node.AsBinaryExpression().Left()) } else { b.bindAssignmentTargetFlow(node) } @@ -1861,9 +1868,9 @@ func (b *Binder) bindWhileStatement(node *ast.Node) { postWhileLabel := b.createBranchLabel() b.addAntecedent(preWhileLabel, b.currentFlow) b.currentFlow = preWhileLabel - b.bindCondition(stmt.Expression, preBodyLabel, postWhileLabel) + b.bindCondition(stmt.Expression(), preBodyLabel, postWhileLabel) b.currentFlow = b.finishFlowLabel(preBodyLabel) - b.bindIterativeStatement(stmt.Statement, postWhileLabel, preWhileLabel) + b.bindIterativeStatement(stmt.Statement(), postWhileLabel, preWhileLabel) b.addAntecedent(preWhileLabel, b.currentFlow) b.currentFlow = b.finishFlowLabel(postWhileLabel) } @@ -1875,25 +1882,25 @@ func (b *Binder) bindDoStatement(node *ast.Node) { postDoLabel := b.createBranchLabel() b.addAntecedent(preDoLabel, b.currentFlow) b.currentFlow = preDoLabel - b.bindIterativeStatement(stmt.Statement, postDoLabel, preConditionLabel) + b.bindIterativeStatement(stmt.Statement(), postDoLabel, preConditionLabel) b.addAntecedent(preConditionLabel, b.currentFlow) b.currentFlow = b.finishFlowLabel(preConditionLabel) - b.bindCondition(stmt.Expression, preDoLabel, postDoLabel) + b.bindCondition(stmt.Expression(), preDoLabel, postDoLabel) b.currentFlow = b.finishFlowLabel(postDoLabel) } func (b *Binder) bindForStatement(node *ast.Node) { stmt := node.AsForStatement() - b.bind(stmt.Initializer) + b.bind(stmt.Initializer()) if b.currentFlow == b.unreachableFlow { // Unlike while/do, the for-loop initializer is bound inside this function before the loop's // flow graph is constructed. If it makes flow unreachable (e.g. a throwing IIFE), addAntecedent // will filter out the unreachable entry to preLoopLabel, leaving only the back-edge from the // incrementor. This creates a cycle with no exit that crashes isReachableFlowNodeWorker. // Bail out early and just bind the remaining children with unreachable flow. - b.bind(stmt.Condition) - b.bind(stmt.Statement) - b.bind(stmt.Incrementor) + b.bind(stmt.Condition()) + b.bind(stmt.Statement()) + b.bind(stmt.Incrementor()) return } preLoopLabel := b.setContinueTarget(node, b.createLoopLabel()) @@ -1902,27 +1909,27 @@ func (b *Binder) bindForStatement(node *ast.Node) { postLoopLabel := b.createBranchLabel() b.addAntecedent(preLoopLabel, b.currentFlow) b.currentFlow = preLoopLabel - b.bindCondition(stmt.Condition, preBodyLabel, postLoopLabel) + b.bindCondition(stmt.Condition(), preBodyLabel, postLoopLabel) b.currentFlow = b.finishFlowLabel(preBodyLabel) - b.bindIterativeStatement(stmt.Statement, postLoopLabel, preIncrementorLabel) + b.bindIterativeStatement(stmt.Statement(), postLoopLabel, preIncrementorLabel) b.addAntecedent(preIncrementorLabel, b.currentFlow) b.currentFlow = b.finishFlowLabel(preIncrementorLabel) - b.bind(stmt.Incrementor) + b.bind(stmt.Incrementor()) b.addAntecedent(preLoopLabel, b.currentFlow) b.currentFlow = b.finishFlowLabel(postLoopLabel) } func (b *Binder) bindForInOrForOfStatement(node *ast.Node) { stmt := node.AsForInOrOfStatement() - b.bind(stmt.Expression) + b.bind(stmt.Expression()) if b.currentFlow == b.unreachableFlow { // Like the for-loop initializer, the for-in/for-of expression is bound before the loop's // flow graph is constructed. If it makes flow unreachable (e.g. a throwing IIFE), addAntecedent // will filter out the unreachable entry to preLoopLabel, leaving only the back-edge from the // loop body. This creates a cycle with no exit that crashes isReachableFlowNodeWorker. // Bail out early and just bind the remaining children with unreachable flow. - b.bind(stmt.Initializer) - b.bind(stmt.Statement) + b.bind(stmt.Initializer()) + b.bind(stmt.Statement()) return } preLoopLabel := b.setContinueTarget(node, b.createLoopLabel()) @@ -1930,14 +1937,14 @@ func (b *Binder) bindForInOrForOfStatement(node *ast.Node) { b.addAntecedent(preLoopLabel, b.currentFlow) b.currentFlow = preLoopLabel if node.Kind == ast.KindForOfStatement { - b.bind(stmt.AwaitModifier) + b.bind(stmt.AwaitModifier()) } b.addAntecedent(postLoopLabel, b.currentFlow) - b.bind(stmt.Initializer) - if stmt.Initializer.Kind != ast.KindVariableDeclarationList { - b.bindAssignmentTargetFlow(stmt.Initializer) + b.bind(stmt.Initializer()) + if stmt.Initializer().Kind != ast.KindVariableDeclarationList { + b.bindAssignmentTargetFlow(stmt.Initializer()) } - b.bindIterativeStatement(stmt.Statement, postLoopLabel, preLoopLabel) + b.bindIterativeStatement(stmt.Statement(), postLoopLabel, preLoopLabel) b.addAntecedent(preLoopLabel, b.currentFlow) b.currentFlow = b.finishFlowLabel(postLoopLabel) } @@ -1947,12 +1954,12 @@ func (b *Binder) bindIfStatement(node *ast.Node) { thenLabel := b.createBranchLabel() elseLabel := b.createBranchLabel() postIfLabel := b.createBranchLabel() - b.bindCondition(stmt.Expression, thenLabel, elseLabel) + b.bindCondition(stmt.Expression(), thenLabel, elseLabel) b.currentFlow = b.finishFlowLabel(thenLabel) - b.bind(stmt.ThenStatement) + b.bind(stmt.ThenStatement()) b.addAntecedent(postIfLabel, b.currentFlow) b.currentFlow = b.finishFlowLabel(elseLabel) - b.bind(stmt.ElseStatement) + b.bind(stmt.ElseStatement()) b.addAntecedent(postIfLabel, b.currentFlow) b.currentFlow = b.finishFlowLabel(postIfLabel) } @@ -2024,14 +2031,14 @@ func (b *Binder) bindTryStatement(node *ast.Node) { normalExitLabel := b.createBranchLabel() returnLabel := b.createBranchLabel() exceptionLabel := b.createBranchLabel() - if stmt.FinallyBlock != nil { + if stmt.FinallyBlock() != nil { b.currentReturnTarget = returnLabel } b.addAntecedent(exceptionLabel, b.currentFlow) b.currentExceptionTarget = exceptionLabel - b.bind(stmt.TryBlock) + b.bind(stmt.TryBlock()) b.addAntecedent(normalExitLabel, b.currentFlow) - if stmt.CatchClause != nil { + if stmt.CatchClause() != nil { // Start of catch clause is the target of exceptions from try block. b.currentFlow = b.finishFlowLabel(exceptionLabel) // The currentExceptionTarget now represents control flows from exceptions in the catch clause. @@ -2040,12 +2047,12 @@ func (b *Binder) bindTryStatement(node *ast.Node) { exceptionLabel = b.createBranchLabel() b.addAntecedent(exceptionLabel, b.currentFlow) b.currentExceptionTarget = exceptionLabel - b.bind(stmt.CatchClause) + b.bind(stmt.CatchClause()) b.addAntecedent(normalExitLabel, b.currentFlow) } b.currentReturnTarget = saveReturnTarget b.currentExceptionTarget = saveExceptionTarget - if stmt.FinallyBlock != nil { + if stmt.FinallyBlock() != nil { // Possible ways control can reach the finally block: // 1) Normal completion of try block of a try-finally or try-catch-finally // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally @@ -2063,7 +2070,7 @@ func (b *Binder) bindTryStatement(node *ast.Node) { finallyLabel := b.createBranchLabel() finallyLabel.Antecedents = b.combineFlowLists(normalExitLabel.Antecedents, b.combineFlowLists(exceptionLabel.Antecedents, returnLabel.Antecedents)) b.currentFlow = finallyLabel - b.bind(stmt.FinallyBlock) + b.bind(stmt.FinallyBlock()) if b.currentFlow.Flags&ast.FlowFlagsUnreachable != 0 { // If the end of the finally block is unreachable, the end of the entire try statement is unreachable. b.currentFlow = b.unreachableFlow @@ -2095,14 +2102,14 @@ func (b *Binder) bindTryStatement(node *ast.Node) { func (b *Binder) bindSwitchStatement(node *ast.Node) { stmt := node.AsSwitchStatement() postSwitchLabel := b.createBranchLabel() - b.bind(stmt.Expression) + b.bind(stmt.Expression()) saveBreakTarget := b.currentBreakTarget savePreSwitchCaseFlow := b.preSwitchCaseFlow b.currentBreakTarget = postSwitchLabel b.preSwitchCaseFlow = b.currentFlow - b.bind(stmt.CaseBlock) + b.bind(stmt.CaseBlock()) b.addAntecedent(postSwitchLabel, b.currentFlow) - hasDefault := core.Some(stmt.CaseBlock.AsCaseBlock().Clauses.Nodes, func(c *ast.Node) bool { + hasDefault := core.Some(stmt.CaseBlock().AsCaseBlock().Clauses().Nodes, func(c *ast.Node) bool { return c.Kind == ast.KindDefaultClause }) if !hasDefault { @@ -2114,8 +2121,8 @@ func (b *Binder) bindSwitchStatement(node *ast.Node) { } func (b *Binder) bindCaseBlock(node *ast.Node) { - switchStatement := node.Parent - clauses := node.AsCaseBlock().Clauses.Nodes + switchStatement := node.Parent() + clauses := node.AsCaseBlock().Clauses().Nodes isNarrowingSwitch := switchStatement.Expression().Kind == ast.KindTrueKeyword || isNarrowingExpression(switchStatement.Expression()) var fallthroughFlow *ast.FlowNode = b.unreachableFlow for i := 0; i < len(clauses); i++ { @@ -2146,19 +2153,19 @@ func (b *Binder) bindCaseBlock(node *ast.Node) { func (b *Binder) bindCaseOrDefaultClause(node *ast.Node) { clause := node.AsCaseOrDefaultClause() - if clause.Expression != nil { + if clause.Expression() != nil { saveCurrentFlow := b.currentFlow b.currentFlow = b.preSwitchCaseFlow - b.bind(clause.Expression) + b.bind(clause.Expression()) b.currentFlow = saveCurrentFlow } - b.bindEach(clause.Statements.Nodes) + b.bindEach(clause.Statements().Nodes) } func (b *Binder) bindExpressionStatement(node *ast.Node) { stmt := node.AsExpressionStatement() - b.bind(stmt.Expression) - b.maybeBindExpressionFlowIfCall(stmt.Expression) + b.bind(stmt.Expression()) + b.maybeBindExpressionFlowIfCall(stmt.Expression()) } func (b *Binder) maybeBindExpressionFlowIfCall(node *ast.Node) { @@ -2176,16 +2183,16 @@ func (b *Binder) bindLabeledStatement(node *ast.Node) { postStatementLabel := b.createBranchLabel() b.activeLabelList = &ActiveLabel{ next: b.activeLabelList, - name: stmt.Label.Text(), + name: stmt.Label().Text(), breakTarget: postStatementLabel, continueTarget: nil, referenced: false, } - b.bind(stmt.Label) - b.bind(stmt.Statement) + b.bind(stmt.Label()) + b.bind(stmt.Statement()) if !b.activeLabelList.referenced { // Mark the label as unused; the checker will decide whether to report it - stmt.Label.Flags |= ast.NodeFlagsUnreachable + stmt.Label().Flags |= ast.NodeFlagsUnreachable } b.activeLabelList = b.activeLabelList.next b.addAntecedent(postStatementLabel, b.currentFlow) @@ -2204,7 +2211,7 @@ func (b *Binder) bindPrefixUnaryExpressionFlow(node *ast.Node) { } else { b.bindEachChild(node) if expr.Operator == ast.KindPlusPlusToken || expr.Operator == ast.KindMinusMinusToken { - b.bindAssignmentTargetFlow(expr.Operand) + b.bindAssignmentTargetFlow(expr.Operand()) } } } @@ -2213,7 +2220,7 @@ func (b *Binder) bindPostfixUnaryExpressionFlow(node *ast.Node) { expr := node.AsPostfixUnaryExpression() b.bindEachChild(node) if expr.Operator == ast.KindPlusPlusToken || expr.Operator == ast.KindMinusMinusToken { - b.bindAssignmentTargetFlow(expr.Operand) + b.bindAssignmentTargetFlow(expr.Operand()) } } @@ -2221,25 +2228,25 @@ func (b *Binder) bindDestructuringAssignmentFlow(node *ast.Node) { expr := node.AsBinaryExpression() if b.inAssignmentPattern { b.inAssignmentPattern = false - b.bind(expr.OperatorToken) - b.bind(expr.Right) + b.bind(expr.OperatorToken()) + b.bind(expr.Right()) b.inAssignmentPattern = true - b.bind(expr.Left) - b.bind(expr.Type) + b.bind(expr.Left()) + b.bind(expr.Type()) } else { b.inAssignmentPattern = true - b.bind(expr.Left) - b.bind(expr.Type) + b.bind(expr.Left()) + b.bind(expr.Type()) b.inAssignmentPattern = false - b.bind(expr.OperatorToken) - b.bind(expr.Right) + b.bind(expr.OperatorToken()) + b.bind(expr.Right()) } - b.bindAssignmentTargetFlow(expr.Left) + b.bindAssignmentTargetFlow(expr.Left()) } func (b *Binder) bindBinaryExpressionFlow(node *ast.Node) { expr := node.AsBinaryExpression() - operator := expr.OperatorToken.Kind + operator := expr.OperatorToken().Kind if ast.IsLogicalOrCoalescingBinaryOperator(operator) || ast.IsLogicalOrCoalescingAssignmentOperator(operator) { if isTopLevelLogicalExpression(node) { postExpressionLabel := b.createBranchLabel() @@ -2257,21 +2264,21 @@ func (b *Binder) bindBinaryExpressionFlow(node *ast.Node) { b.bindLogicalLikeExpression(node, b.currentTrueTarget, b.currentFalseTarget) } } else { - b.bind(expr.Left) - b.bind(expr.Type) + b.bind(expr.Left()) + b.bind(expr.Type()) if operator == ast.KindCommaToken { - b.maybeBindExpressionFlowIfCall(expr.Left) + b.maybeBindExpressionFlowIfCall(expr.Left()) } - b.bind(expr.OperatorToken) - b.bind(expr.Right) + b.bind(expr.OperatorToken()) + b.bind(expr.Right()) if operator == ast.KindCommaToken { - b.maybeBindExpressionFlowIfCall(expr.Right) + b.maybeBindExpressionFlowIfCall(expr.Right()) } if ast.IsAssignmentOperator(operator) && !ast.IsAssignmentTarget(node) { - b.bindAssignmentTargetFlow(expr.Left) - if operator == ast.KindEqualsToken && expr.Left.Kind == ast.KindElementAccessExpression { - elementAccess := expr.Left.AsElementAccessExpression() - if isNarrowableOperand(elementAccess.Expression) { + b.bindAssignmentTargetFlow(expr.Left()) + if operator == ast.KindEqualsToken && expr.Left().Kind == ast.KindElementAccessExpression { + elementAccess := expr.Left().AsElementAccessExpression() + if isNarrowableOperand(elementAccess.Expression()) { b.currentFlow = b.createFlowMutation(ast.FlowFlagsArrayMutation, b.currentFlow, node) } } @@ -2282,28 +2289,28 @@ func (b *Binder) bindBinaryExpressionFlow(node *ast.Node) { func (b *Binder) bindLogicalLikeExpression(node *ast.Node, trueTarget *ast.FlowLabel, falseTarget *ast.FlowLabel) { expr := node.AsBinaryExpression() preRightLabel := b.createBranchLabel() - if expr.OperatorToken.Kind == ast.KindAmpersandAmpersandToken || expr.OperatorToken.Kind == ast.KindAmpersandAmpersandEqualsToken { - b.bindCondition(expr.Left, preRightLabel, falseTarget) + if expr.OperatorToken().Kind == ast.KindAmpersandAmpersandToken || expr.OperatorToken().Kind == ast.KindAmpersandAmpersandEqualsToken { + b.bindCondition(expr.Left(), preRightLabel, falseTarget) } else { - b.bindCondition(expr.Left, trueTarget, preRightLabel) + b.bindCondition(expr.Left(), trueTarget, preRightLabel) } b.currentFlow = b.finishFlowLabel(preRightLabel) - b.bind(expr.OperatorToken) - if ast.IsLogicalOrCoalescingAssignmentOperator(expr.OperatorToken.Kind) { - b.doWithConditionalBranches((*Binder).bind, expr.Right, trueTarget, falseTarget) - b.bindAssignmentTargetFlow(expr.Left) + b.bind(expr.OperatorToken()) + if ast.IsLogicalOrCoalescingAssignmentOperator(expr.OperatorToken().Kind) { + b.doWithConditionalBranches((*Binder).bind, expr.Right(), trueTarget, falseTarget) + b.bindAssignmentTargetFlow(expr.Left()) b.addAntecedent(trueTarget, b.createFlowCondition(ast.FlowFlagsTrueCondition, b.currentFlow, node)) b.addAntecedent(falseTarget, b.createFlowCondition(ast.FlowFlagsFalseCondition, b.currentFlow, node)) } else { - b.bindCondition(expr.Right, trueTarget, falseTarget) + b.bindCondition(expr.Right(), trueTarget, falseTarget) } } func (b *Binder) bindDeleteExpressionFlow(node *ast.Node) { expr := node.AsDeleteExpression() b.bindEachChild(node) - if expr.Expression.Kind == ast.KindPropertyAccessExpression { - b.bindAssignmentTargetFlow(expr.Expression) + if expr.Expression().Kind == ast.KindPropertyAccessExpression { + b.bindAssignmentTargetFlow(expr.Expression()) } } @@ -2315,14 +2322,14 @@ func (b *Binder) bindConditionalExpressionFlow(node *ast.Node) { saveCurrentFlow := b.currentFlow saveHasFlowEffects := b.hasFlowEffects b.hasFlowEffects = false - b.bindCondition(expr.Condition, trueLabel, falseLabel) + b.bindCondition(expr.Condition(), trueLabel, falseLabel) b.currentFlow = b.finishFlowLabel(trueLabel) - b.bind(expr.QuestionToken) - b.bind(expr.WhenTrue) + b.bind(expr.QuestionToken()) + b.bind(expr.WhenTrue()) b.addAntecedent(postExpressionLabel, b.currentFlow) b.currentFlow = b.finishFlowLabel(falseLabel) - b.bind(expr.ColonToken) - b.bind(expr.WhenFalse) + b.bind(expr.ColonToken()) + b.bind(expr.WhenFalse()) b.addAntecedent(postExpressionLabel, b.currentFlow) if b.hasFlowEffects { b.currentFlow = b.finishFlowLabel(postExpressionLabel) @@ -2334,7 +2341,7 @@ func (b *Binder) bindConditionalExpressionFlow(node *ast.Node) { func (b *Binder) bindVariableDeclarationFlow(node *ast.Node) { b.bindEachChild(node) - if node.Initializer() != nil || ast.IsForInOrOfStatement(node.Parent.Parent) { + if node.Initializer() != nil || ast.IsForInOrOfStatement(node.Parent().Parent()) { b.bindInitializedVariableFlow(node) } } @@ -2423,7 +2430,7 @@ func (b *Binder) bindOptionalChainRest(node *ast.Node) bool { b.bind(node.Name()) case ast.KindElementAccessExpression: b.bind(node.QuestionDotToken()) - b.bind(node.AsElementAccessExpression().ArgumentExpression) + b.bind(node.AsElementAccessExpression().ArgumentExpression()) case ast.KindCallExpression: b.bind(node.QuestionDotToken()) b.bindNodeList(node.TypeArgumentList()) @@ -2440,21 +2447,21 @@ func (b *Binder) bindCallExpressionFlow(node *ast.Node) { // If the target of the call expression is a function expression or arrow function we have // an immediately invoked function expression (IIFE). Initialize the flowNode property to // the current control flow (which includes evaluation of the IIFE arguments). - expr := ast.SkipParentheses(call.Expression) + expr := ast.SkipParentheses(call.Expression()) if expr.Kind == ast.KindFunctionExpression || expr.Kind == ast.KindArrowFunction { - b.bindNodeList(call.TypeArguments) - b.bindEach(call.Arguments.Nodes) - b.bind(call.Expression) + b.bindNodeList(call.TypeArguments()) + b.bindEach(call.Arguments().Nodes) + b.bind(call.Expression()) } else { b.bindEachChild(node) - if call.Expression.Kind == ast.KindSuperKeyword { + if call.Expression().Kind == ast.KindSuperKeyword { b.currentFlow = b.createFlowCall(b.currentFlow, node) } } } - if ast.IsPropertyAccessExpression(call.Expression) { - access := call.Expression.AsPropertyAccessExpression() - if ast.IsIdentifier(access.Name()) && isNarrowableOperand(access.Expression) && ast.IsPushOrUnshiftIdentifier(access.Name()) { + if ast.IsPropertyAccessExpression(call.Expression()) { + access := call.Expression().AsPropertyAccessExpression() + if ast.IsIdentifier(access.Name()) && isNarrowableOperand(access.Expression()) && ast.IsPushOrUnshiftIdentifier(access.Name()) { b.currentFlow = b.createFlowMutation(ast.FlowFlagsArrayMutation, b.currentFlow, node) } } @@ -2475,19 +2482,19 @@ func (b *Binder) bindBindingElementFlow(node *ast.Node) { // - https://tc39.es/ecma262/#sec-runtime-semantics-keyedbindinginitialization // - `BindingElement: BindingPattern Initializer?` elem := node.AsBindingElement() - b.bind(elem.DotDotDotToken) - b.bind(elem.PropertyName) - b.bindInitializer(elem.Initializer) + b.bind(elem.DotDotDotToken()) + b.bind(elem.PropertyName()) + b.bindInitializer(elem.Initializer()) b.bind(elem.Name()) } func (b *Binder) bindParameterFlow(node *ast.Node) { param := node.AsParameterDeclaration() b.bindModifiers(param.Modifiers()) - b.bind(param.DotDotDotToken) - b.bind(param.QuestionToken) - b.bind(param.Type) - b.bindInitializer(param.Initializer) + b.bind(param.DotDotDotToken()) + b.bind(param.QuestionToken()) + b.bind(param.Type()) + b.bindInitializer(param.Initializer()) b.bind(param.Name()) } @@ -2528,7 +2535,7 @@ func setReturnFlowNode(node *ast.Node, returnFlowNode *ast.FlowNode) { } func isGeneratorFunctionExpression(node *ast.Node) bool { - return ast.IsFunctionExpression(node) && node.AsFunctionExpression().AsteriskToken != nil + return ast.IsFunctionExpression(node) && node.AsFunctionExpression().AsteriskToken() != nil } func (b *Binder) addToContainerChain(next *ast.Node) { @@ -2611,7 +2618,7 @@ func GetContainerFlags(node *ast.Node) ContainerFlags { case ast.KindCatchClause, ast.KindForStatement, ast.KindForInStatement, ast.KindForOfStatement, ast.KindCaseBlock: return ContainerFlagsIsBlockScopedContainer | ContainerFlagsHasLocals case ast.KindBlock: - if ast.IsFunctionLike(node.Parent) || ast.IsClassStaticBlockDeclaration(node.Parent) { + if ast.IsFunctionLike(node.Parent()) || ast.IsClassStaticBlockDeclaration(node.Parent()) { return ContainerFlagsNone } else { return ContainerFlagsIsBlockScopedContainer | ContainerFlagsHasLocals @@ -2633,7 +2640,7 @@ func isNarrowingExpression(expr *ast.Node) bool { case ast.KindBinaryExpression: return isNarrowingBinaryExpression(expr.AsBinaryExpression()) case ast.KindPrefixUnaryExpression: - return expr.AsPrefixUnaryExpression().Operator == ast.KindExclamationToken && isNarrowingExpression(expr.AsPrefixUnaryExpression().Operand) + return expr.AsPrefixUnaryExpression().Operator == ast.KindExclamationToken && isNarrowingExpression(expr.AsPrefixUnaryExpression().Operand()) } return false } @@ -2659,25 +2666,25 @@ func isNarrowableReference(node *ast.Node) bool { return isNarrowableReference(node.Expression()) case ast.KindElementAccessExpression: expr := node.AsElementAccessExpression() - return ast.IsStringOrNumericLiteralLike(expr.ArgumentExpression) || - ast.IsEntityNameExpression(expr.ArgumentExpression) && isNarrowableReference(expr.Expression) + return ast.IsStringOrNumericLiteralLike(expr.ArgumentExpression()) || + ast.IsEntityNameExpression(expr.ArgumentExpression()) && isNarrowableReference(expr.Expression()) case ast.KindBinaryExpression: expr := node.AsBinaryExpression() - return expr.OperatorToken.Kind == ast.KindCommaToken && isNarrowableReference(expr.Right) || - ast.IsAssignmentOperator(expr.OperatorToken.Kind) && ast.IsLeftHandSideExpression(expr.Left) + return expr.OperatorToken().Kind == ast.KindCommaToken && isNarrowableReference(expr.Right()) || + ast.IsAssignmentOperator(expr.OperatorToken().Kind) && ast.IsLeftHandSideExpression(expr.Left()) } return false } func hasNarrowableArgument(expr *ast.Node) bool { call := expr.AsCallExpression() - for _, argument := range call.Arguments.Nodes { //nolint:modernize + for _, argument := range call.Arguments().Nodes { //nolint:modernize if containsNarrowableReference(argument) { return true } } - if ast.IsPropertyAccessExpression(call.Expression) { - if containsNarrowableReference(call.Expression.Expression()) { + if ast.IsPropertyAccessExpression(call.Expression()) { + if containsNarrowableReference(call.Expression().Expression()) { return true } } @@ -2685,21 +2692,21 @@ func hasNarrowableArgument(expr *ast.Node) bool { } func isNarrowingBinaryExpression(expr *ast.BinaryExpression) bool { - switch expr.OperatorToken.Kind { + switch expr.OperatorToken().Kind { case ast.KindEqualsToken, ast.KindBarBarEqualsToken, ast.KindAmpersandAmpersandEqualsToken, ast.KindQuestionQuestionEqualsToken: - return containsNarrowableReference(expr.Left) + return containsNarrowableReference(expr.Left()) case ast.KindEqualsEqualsToken, ast.KindExclamationEqualsToken, ast.KindEqualsEqualsEqualsToken, ast.KindExclamationEqualsEqualsToken: - left := ast.SkipParentheses(expr.Left) - right := ast.SkipParentheses(expr.Right) + left := ast.SkipParentheses(expr.Left()) + right := ast.SkipParentheses(expr.Right()) return isNarrowableOperand(left) || isNarrowableOperand(right) || isNarrowingTypeOfOperands(right, left) || isNarrowingTypeOfOperands(left, right) || (ast.IsBooleanLiteral(right) && isNarrowingExpression(left) || ast.IsBooleanLiteral(left) && isNarrowingExpression(right)) case ast.KindInstanceOfKeyword: - return isNarrowableOperand(expr.Left) + return isNarrowableOperand(expr.Left()) case ast.KindInKeyword: - return isNarrowingExpression(expr.Right) + return isNarrowingExpression(expr.Right()) case ast.KindCommaToken: - return isNarrowingExpression(expr.Right) + return isNarrowingExpression(expr.Right()) } return false } @@ -2710,11 +2717,11 @@ func isNarrowableOperand(expr *ast.Node) bool { return isNarrowableOperand(expr.Expression()) case ast.KindBinaryExpression: binary := expr.AsBinaryExpression() - switch binary.OperatorToken.Kind { + switch binary.OperatorToken().Kind { case ast.KindEqualsToken: - return isNarrowableOperand(binary.Left) + return isNarrowableOperand(binary.Left()) case ast.KindCommaToken: - return isNarrowableOperand(binary.Right) + return isNarrowableOperand(binary.Right()) } } return containsNarrowableReference(expr) @@ -2747,7 +2754,7 @@ func (b *Binder) addDiagnostic(diagnostic *ast.Diagnostic) { func isSignedNumericLiteral(node *ast.Node) bool { if node.Kind == ast.KindPrefixUnaryExpression { node := node.AsPrefixUnaryExpression() - return (node.Operator == ast.KindPlusToken || node.Operator == ast.KindMinusToken) && ast.IsNumericLiteral(node.Operand) + return (node.Operator == ast.KindPlusToken || node.Operator == ast.KindMinusToken) && ast.IsNumericLiteral(node.Operand()) } return false } @@ -2765,8 +2772,8 @@ func isFunctionSymbol(symbol *ast.Symbol) bool { } if ast.IsVariableDeclaration(d) { varDecl := d.AsVariableDeclaration() - if varDecl.Initializer != nil { - return ast.IsFunctionLike(varDecl.Initializer) + if varDecl.Initializer() != nil { + return ast.IsFunctionLike(varDecl.Initializer()) } } } @@ -2774,22 +2781,22 @@ func isFunctionSymbol(symbol *ast.Symbol) bool { } func isStatementCondition(node *ast.Node) bool { - switch node.Parent.Kind { + switch node.Parent().Kind { case ast.KindIfStatement, ast.KindWhileStatement, ast.KindDoStatement: - return node.Parent.Expression() == node + return node.Parent().Expression() == node case ast.KindForStatement: - return node.Parent.AsForStatement().Condition == node + return node.Parent().AsForStatement().Condition() == node case ast.KindConditionalExpression: - return node.Parent.AsConditionalExpression().Condition == node + return node.Parent().AsConditionalExpression().Condition() == node } return false } func isTopLevelLogicalExpression(node *ast.Node) bool { - for ast.IsParenthesizedExpression(node.Parent) || ast.IsPrefixUnaryExpression(node.Parent) && node.Parent.AsPrefixUnaryExpression().Operator == ast.KindExclamationToken { - node = node.Parent + for ast.IsParenthesizedExpression(node.Parent()) || ast.IsPrefixUnaryExpression(node.Parent()) && node.Parent().AsPrefixUnaryExpression().Operator == ast.KindExclamationToken { + node = node.Parent() } - return !isStatementCondition(node) && !ast.IsLogicalExpression(node.Parent) && !(ast.IsOptionalChain(node.Parent) && node.Parent.Expression() == node) + return !isStatementCondition(node) && !ast.IsLogicalExpression(node.Parent()) && !(ast.IsOptionalChain(node.Parent()) && node.Parent().Expression() == node) } func isAssignmentDeclaration(decl *ast.Node) bool { diff --git a/tsc/internal/binder/nameresolver.go b/tsc/internal/binder/nameresolver.go index 5c1928ec4b6fd..3e3f0dd947678 100644 --- a/tsc/internal/binder/nameresolver.go +++ b/tsc/internal/binder/nameresolver.go @@ -43,11 +43,11 @@ loop: // If lastLocation is the name of a namespace or enum, skip the parent since it will have is own locals that could // conflict. lastLocation = location - location = location.Parent + location = location.Parent() } isModuleAttributes := ast.IsModuleDeclaration(location) && - location.AsModuleDeclaration().Attributes != nil && - lastLocation == location.AsModuleDeclaration().Attributes + location.AsModuleDeclaration().Attributes() != nil && + lastLocation == location.AsModuleDeclaration().Attributes() locals := location.Locals() // Locals of a source file are not in scope (because they get merged into the global symbol table) if locals != nil && !ast.IsGlobalSourceFile(location) { @@ -91,7 +91,7 @@ loop: } else if location.Kind == ast.KindConditionalType { // A type parameter declared using 'infer T' in a conditional type is visible only in // the true branch of the conditional type. - useResult = lastLocation == location.AsConditionalTypeNode().TrueType + useResult = lastLocation == location.AsConditionalTypeNode().TrueType() } if useResult { break loop @@ -167,7 +167,7 @@ loop: } case ast.KindPropertyDeclaration: if !ast.IsStatic(location) { - ctor := ast.FindConstructorDeclaration(location.Parent) + ctor := ast.FindConstructorDeclaration(location.Parent()) if ctor != nil && ctor.Locals() != nil { if r.lookup(ctor.Locals(), name, meaning&ast.SymbolFlagsValue) != nil { // Remember the property node, it will be used later to report appropriate error @@ -202,8 +202,8 @@ loop: } } case ast.KindExpressionWithTypeArguments: - if lastLocation == location.Expression() && ast.IsHeritageClause(location.Parent) && location.Parent.AsHeritageClause().Token == ast.KindExtendsKeyword { - container := location.Parent.Parent + 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) if result != nil { @@ -222,7 +222,7 @@ loop: // [foo()]() { } // <-- Reference to T from class's own computed property // } case ast.KindComputedPropertyName: - grandparent = location.Parent.Parent + grandparent = location.Parent().Parent() if ast.IsClassLike(grandparent) || ast.IsInterfaceDeclaration(grandparent) { // A reference to this grandparent's type parameters would be an error result = r.lookup(r.getSymbolOfDeclaration(grandparent).Members, name, meaning&ast.SymbolFlagsType) @@ -259,8 +259,8 @@ loop: // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. // } // - if location.Parent != nil && location.Parent.Kind == ast.KindParameter { - location = location.Parent + if location.Parent() != nil && location.Parent().Kind == ast.KindParameter { + location = location.Parent() } // function y() {} // class C { @@ -273,12 +273,12 @@ loop: // declare function y(x: T): any; // @param(1 as T) // <-- T should resolve to the type alias outside of class C // class C {} - if location.Parent != nil && (ast.IsClassElement(location.Parent) || location.Parent.Kind == ast.KindClassDeclaration) { - location = location.Parent + if location.Parent() != nil && (ast.IsClassElement(location.Parent()) || location.Parent().Kind == ast.KindClassDeclaration) { + location = location.Parent() } case ast.KindParameter: parameterDeclaration := location.AsParameterDeclaration() - if lastLocation != nil && (lastLocation == parameterDeclaration.Initializer || + if lastLocation != nil && (lastLocation == parameterDeclaration.Initializer() || lastLocation == parameterDeclaration.Name() && ast.IsBindingPattern(lastLocation)) { if associatedDeclarationForContainingInitializerOrBindingName == nil { associatedDeclarationForContainingInitializerOrBindingName = location @@ -286,7 +286,7 @@ loop: } case ast.KindBindingElement: bindingElement := location.AsBindingElement() - if lastLocation != nil && (lastLocation == bindingElement.Initializer || + if lastLocation != nil && (lastLocation == bindingElement.Initializer() || lastLocation == bindingElement.Name() && ast.IsBindingPattern(lastLocation)) { if ast.IsPartOfParameterDeclaration(location) && associatedDeclarationForContainingInitializerOrBindingName == nil { associatedDeclarationForContainingInitializerOrBindingName = location @@ -294,16 +294,16 @@ loop: } case ast.KindInferType: if meaning&ast.SymbolFlagsTypeParameter != 0 { - parameterName := location.AsInferTypeNode().TypeParameter.AsTypeParameterDeclaration().Name() + parameterName := location.AsInferTypeNode().TypeParameter().AsTypeParameterDeclaration().Name() if parameterName != nil && name == parameterName.Text() { - result = location.AsInferTypeNode().TypeParameter.Symbol() + result = location.AsInferTypeNode().TypeParameter().Symbol() break loop } } case ast.KindExportSpecifier: exportSpecifier := location.AsExportSpecifier() - if lastLocation != nil && lastLocation == exportSpecifier.PropertyName && location.Parent.Parent.ModuleSpecifier() != nil { - location = location.Parent.Parent.Parent + if lastLocation != nil && lastLocation == exportSpecifier.PropertyName() && location.Parent().Parent().ModuleSpecifier() != nil { + location = location.Parent().Parent().Parent() } } if isSelfReferenceLocation(location, lastLocation) { @@ -314,7 +314,7 @@ loop: // getEffectiveContainerForJSDocTemplateTag/getHostSignatureFromJSDoc instead of location.parent. // This is a no-op currently because JSDoc nodes have no locals and getEffectiveJSDocHost is not // fully ported for JS assignment patterns. - location = location.Parent + location = location.Parent() } // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself. @@ -328,8 +328,8 @@ loop: result = r.lookup(r.Globals, name, meaning|ast.SymbolFlagsGlobalLookup) } if result == nil { - if originalLocation != nil && ast.IsInJSFile(originalLocation) && originalLocation.Parent != nil { - if ast.IsRequireCall(originalLocation.Parent, false /*requireStringLiteralLikeArgument*/) { + if originalLocation != nil && ast.IsInJSFile(originalLocation) && originalLocation.Parent() != nil { + if ast.IsRequireCall(originalLocation.Parent(), false /*requireStringLiteralLikeArgument*/) { return r.RequireSymbol } } @@ -379,7 +379,7 @@ func (r *NameResolver) useOuterVariableScopeInParameter(result *ast.Symbol, loca func (r *NameResolver) requiresScopeChange(node *ast.Node) bool { d := node.AsParameterDeclaration() - return r.requiresScopeChangeWorker(d.Name()) || d.Initializer != nil && r.requiresScopeChangeWorker(d.Initializer) + return r.requiresScopeChangeWorker(d.Name()) || d.Initializer() != nil && r.requiresScopeChangeWorker(d.Initializer()) } func (r *NameResolver) requiresScopeChangeWorker(node *ast.Node) bool { @@ -397,7 +397,7 @@ func (r *NameResolver) requiresScopeChangeWorker(node *ast.Node) bool { if ast.IsNullishCoalesce(node) || ast.IsOptionalChain(node) { return r.CompilerOptions.GetEmitScriptTarget() < core.ScriptTargetES2020 } - if ast.IsBindingElement(node) && node.AsBindingElement().DotDotDotToken != nil && ast.IsObjectBindingPattern(node.Parent) { + if ast.IsBindingElement(node) && node.AsBindingElement().DotDotDotToken() != nil && ast.IsObjectBindingPattern(node.Parent()) { return r.CompilerOptions.GetEmitScriptTarget() < core.ScriptTargetES2017 } if ast.IsTypeNode(node) { @@ -476,7 +476,7 @@ func getIsDeferredContext(location *ast.Node, lastLocation *ast.Node) bool { return false } // generator functions and async functions are not inlined in control flow when immediately invoked - if location.BodyData().AsteriskToken != nil || ast.HasSyntacticModifier(location, ast.ModifierFlagsAsync) { + if location.BodyData().AsteriskToken() != nil || ast.HasSyntacticModifier(location, ast.ModifierFlagsAsync) { return true } return ast.GetImmediatelyInvokedFunctionExpression(location) == nil @@ -485,7 +485,7 @@ func getIsDeferredContext(location *ast.Node, lastLocation *ast.Node) bool { func isTypeParameterSymbolDeclaredInContainer(symbol *ast.Symbol, container *ast.Node) bool { for _, decl := range symbol.Declarations { if decl.Kind == ast.KindTypeParameter { - parent := decl.Parent + parent := decl.Parent() if parent == container { return true } diff --git a/tsc/internal/binder/referenceresolver.go b/tsc/internal/binder/referenceresolver.go index fbc6e5a24d7ff..9397ca5c76bcf 100644 --- a/tsc/internal/binder/referenceresolver.go +++ b/tsc/internal/binder/referenceresolver.go @@ -87,8 +87,8 @@ func (r *referenceResolver) getReferencedValueSymbol(reference *ast.IdentifierNo } location := reference - if startInDeclarationContainer && reference.Parent != nil && ast.IsDeclaration(reference.Parent) && reference.Parent.Name() == reference { - location = ast.GetDeclarationContainer(reference.Parent) + if startInDeclarationContainer && reference.Parent() != nil && ast.IsDeclaration(reference.Parent()) && reference.Parent().Name() == reference { + location = ast.GetDeclarationContainer(reference.Parent()) } if r.hooks.ResolveName != nil { @@ -119,10 +119,10 @@ func (r *referenceResolver) isTypeOnlyAliasDeclaration(symbol *ast.Symbol) bool if node.IsTypeOnly() { return true } - node = node.Parent + node = node.Parent() continue case ast.KindNamedImports, ast.KindNamedExports: - node = node.Parent + node = node.Parent() continue } break @@ -153,7 +153,7 @@ func (r *referenceResolver) GetReferencedExportContainer(node *ast.IdentifierNod // declaration, we need to start resolution at the declaration's container. // Otherwise, we could incorrectly resolve the export as the // declaration if it contains an exported member with the same name. - startInDeclarationContainer := node.Parent != nil && (node.Parent.Kind == ast.KindModuleDeclaration || node.Parent.Kind == ast.KindEnumDeclaration) && node == node.Parent.Name() + startInDeclarationContainer := node.Parent() != nil && (node.Parent().Kind == ast.KindModuleDeclaration || node.Parent().Kind == ast.KindEnumDeclaration) && node == node.Parent().Name() if symbol := r.getReferencedValueSymbol(node, startInDeclarationContainer); symbol != nil { if symbol.Flags&ast.SymbolFlagsExportValue != 0 { // If we reference an exported entity within the same module declaration, then whether @@ -180,7 +180,7 @@ func (r *referenceResolver) GetReferencedExportContainer(node *ast.IdentifierNod isMatchingContainer := func(n *ast.Node) bool { return (n.Kind == ast.KindModuleDeclaration || n.Kind == ast.KindEnumDeclaration) && r.getSymbolOfDeclaration(n) == parentSymbol } - return ast.FindAncestor(node.Parent, isMatchingContainer) + return ast.FindAncestor(node.Parent(), isMatchingContainer) } } diff --git a/tsc/internal/checker/checker.go b/tsc/internal/checker/checker.go index 7bcc8d6cf2ced..cddef001053cf 100644 --- a/tsc/internal/checker/checker.go +++ b/tsc/internal/checker/checker.go @@ -1348,7 +1348,7 @@ func (c *Checker) initializeChecker() { for _, augmentation := range list { // Merge 'global' module augmentations. This needs to be done after global symbol table is initialized to // make sure that all ambient modules are indexed - if ast.IsGlobalScopeAugmentation(augmentation.Parent) { + if ast.IsGlobalScopeAugmentation(augmentation.Parent()) { c.mergeModuleAugmentation(augmentation) } } @@ -1389,7 +1389,7 @@ func (c *Checker) initializeChecker() { // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed for _, list := range augmentations { for _, augmentation := range list { - if !ast.IsGlobalScopeAugmentation(augmentation.Parent) { + if !ast.IsGlobalScopeAugmentation(augmentation.Parent()) { c.mergeModuleAugmentation(augmentation) } } @@ -1436,7 +1436,7 @@ func (c *Checker) mergePatternAmbientModules() { } func (c *Checker) mergeModuleAugmentation(moduleName *ast.Node) { - moduleNode := moduleName.Parent + moduleNode := moduleName.Parent() moduleAugmentation := moduleNode.AsModuleDeclaration() if moduleAugmentation.Symbol.Declarations[0] != moduleNode { // this is a combined symbol for multiple augmentations within the same file. @@ -1450,7 +1450,7 @@ func (c *Checker) mergeModuleAugmentation(moduleName *ast.Node) { // find a module that about to be augmented // do not validate names of augmentations that are defined in ambient context var moduleNotFoundError *diagnostics.Message - if moduleName.Parent.Parent.Flags&ast.NodeFlagsAmbient == 0 { + if moduleName.Parent().Parent().Flags&ast.NodeFlagsAmbient == 0 { moduleNotFoundError = diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found } // We ban import attributes on module augmentation declarations. @@ -1563,7 +1563,7 @@ func (c *Checker) checkAndReportErrorForInvalidInitializer(errorLocation *ast.No // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed // with emitStandardClassFields because the scope semantics are different. prop := propertyWithInvalidInitializer.AsPropertyDeclaration() - message := core.IfElse(errorLocation != nil && prop.Type != nil && prop.Type.Loc.ContainsInclusive(errorLocation.Pos()), + message := core.IfElse(errorLocation != nil && prop.Type() != nil && prop.Type().Loc.ContainsInclusive(errorLocation.Pos()), diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor) c.error(errorLocation, message, scanner.DeclarationNameToString(prop.Name()), name) @@ -1577,9 +1577,9 @@ func (c *Checker) checkAndReportErrorForMissingPrefix(errorLocation *ast.Node, n return false } container := c.getThisContainer(errorLocation, false /*includeArrowFunctions*/, false /*includeClassComputedPropertyName*/) - for location := container; location.Parent != nil; location = location.Parent { - if ast.IsClassLike(location.Parent) { - classSymbol := c.getSymbolOfDeclaration(location.Parent) + for location := container; location.Parent() != nil; location = location.Parent() { + if ast.IsClassLike(location.Parent()) { + classSymbol := c.getSymbolOfDeclaration(location.Parent()) if classSymbol == nil { break } @@ -1610,7 +1610,7 @@ func (c *Checker) onFailedToResolveSymbol(errorLocation *ast.Node, name string, if isConstTypeReferenceName(errorLocation) { return } - if errorLocation != nil && (errorLocation.Parent.Kind == ast.KindJSDocLink || + if errorLocation != nil && (errorLocation.Parent().Kind == ast.KindJSDocLink || c.checkAndReportErrorForMissingPrefix(errorLocation, name) || c.checkAndReportErrorForExtendingInterface(errorLocation) || c.checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) || @@ -1652,10 +1652,10 @@ func (c *Checker) checkAndReportErrorForUsingTypeAsNamespace(errorLocation *ast. if meaning == ast.SymbolFlagsNamespace { symbol := c.resolveSymbol(c.resolveName(errorLocation, name, ast.SymbolFlagsType&^ast.SymbolFlagsNamespace, nil /*nameNotFoundMessage*/, false /*isUse*/, false /*excludeGlobals*/)) if symbol != nil { - parent := errorLocation.Parent + parent := errorLocation.Parent() if ast.IsQualifiedName(parent) { - debug.Assert(parent.AsQualifiedName().Left == errorLocation, "Should only be resolving left side of qualified name as a namespace") - propName := parent.AsQualifiedName().Right.Text() + debug.Assert(parent.AsQualifiedName().Left() == errorLocation, "Should only be resolving left side of qualified name as a namespace") + propName := parent.AsQualifiedName().Right().Text() propType := c.getPropertyOfType(c.getDeclaredTypeOfSymbol(symbol), propName) if propType != nil { c.error(parent, 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, name, propName) @@ -1670,7 +1670,7 @@ func (c *Checker) checkAndReportErrorForUsingTypeAsNamespace(errorLocation *ast. } func (c *Checker) checkAndReportErrorForExportingPrimitiveType(errorLocation *ast.Node, name string) bool { - if isPrimitiveTypeName(name) && errorLocation.Parent.Kind == ast.KindExportSpecifier { + if isPrimitiveTypeName(name) && errorLocation.Parent().Kind == ast.KindExportSpecifier { c.error(errorLocation, diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name) return true } @@ -1705,15 +1705,15 @@ func (c *Checker) checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocatio func (c *Checker) checkAndReportErrorForUsingTypeAsValue(errorLocation *ast.Node, name string, meaning ast.SymbolFlags) bool { if meaning&ast.SymbolFlagsValue != 0 { if isPrimitiveTypeName(name) { - grandparent := errorLocation.Parent.Parent - if grandparent != nil && grandparent.Parent != nil && ast.IsHeritageClause(grandparent) { + grandparent := errorLocation.Parent().Parent() + if grandparent != nil && grandparent.Parent() != nil && ast.IsHeritageClause(grandparent) { heritageKind := grandparent.AsHeritageClause().Token - containerKind := grandparent.Parent.Kind + containerKind := grandparent.Parent().Kind if containerKind == ast.KindInterfaceDeclaration && heritageKind == ast.KindExtendsKeyword { c.error(errorLocation, diagnostics.An_interface_cannot_extend_a_primitive_type_like_0_It_can_only_extend_other_named_object_types, name) - } else if ast.IsClassLike(grandparent.Parent) && heritageKind == ast.KindExtendsKeyword { + } else if ast.IsClassLike(grandparent.Parent()) && heritageKind == ast.KindExtendsKeyword { c.error(errorLocation, diagnostics.A_class_cannot_extend_a_primitive_type_like_0_Classes_can_only_extend_constructable_values, name) - } else if ast.IsClassLike(grandparent.Parent) && heritageKind == ast.KindImplementsKeyword { + } else if ast.IsClassLike(grandparent.Parent()) && heritageKind == ast.KindImplementsKeyword { c.error(errorLocation, diagnostics.A_class_cannot_implement_a_primitive_type_like_0_It_can_only_implement_other_named_object_types, name) } } else { @@ -1750,7 +1750,7 @@ func isES2015OrLaterConstructorName(s string) bool { func (c *Checker) maybeMappedType(node *ast.Node, symbol *ast.Symbol) bool { for { - node = node.Parent + node = node.Parent() if !(ast.IsComputedPropertyName(node) || ast.IsPropertySignatureDeclaration(node)) { break } @@ -1896,7 +1896,7 @@ func (c *Checker) onSuccessfullyResolvedSymbol(errorLocation *ast.Node, result * // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself if candidate == c.getSymbolOfDeclaration(associatedDeclarationForContainingInitializerOrBindingName) { c.error(errorLocation, diagnostics.Parameter_0_cannot_reference_itself, scanner.DeclarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.Name())) - } else if candidate.ValueDeclaration != nil && candidate.ValueDeclaration.Pos() > associatedDeclarationForContainingInitializerOrBindingName.Pos() && root.Parent.Locals() != nil && c.getSymbol(root.Parent.Locals(), candidate.Name, meaning) == candidate { + } else if candidate.ValueDeclaration != nil && candidate.ValueDeclaration.Pos() > associatedDeclarationForContainingInitializerOrBindingName.Pos() && root.Parent().Locals() != nil && c.getSymbol(root.Parent().Locals(), candidate.Name, meaning) == candidate { c.error(errorLocation, diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, scanner.DeclarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.Name()), scanner.DeclarationNameToString(errorLocation)) } } @@ -1974,7 +1974,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.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: @@ -1994,15 +1994,15 @@ func (c *Checker) isBlockScopedNameDeclaredBeforeUse(declaration *ast.Node, usag // except when used in a function that is not an IIFE (e.g., `@dec(() => A.x) class A { ... }`) container := usage for container != nil && container != declaration { - if ast.IsComputedPropertyName(container) && container.Parent.Parent == declaration || - !c.legacyDecorators && ast.IsDecorator(container) && (container.Parent == declaration || - ast.IsMethodDeclaration(container.Parent) && container.Parent.Parent == declaration || - ast.IsAccessor(container.Parent) && container.Parent.Parent == declaration || - ast.IsPropertyDeclaration(container.Parent) && container.Parent.Parent == declaration || - ast.IsParameterDeclaration(container.Parent) && container.Parent.Parent.Parent == declaration) { + if ast.IsComputedPropertyName(container) && container.Parent().Parent() == declaration || + !c.legacyDecorators && ast.IsDecorator(container) && (container.Parent() == declaration || + ast.IsMethodDeclaration(container.Parent()) && container.Parent().Parent() == declaration || + ast.IsAccessor(container.Parent()) && container.Parent().Parent() == declaration || + ast.IsPropertyDeclaration(container.Parent()) && container.Parent().Parent() == declaration || + ast.IsParameterDeclaration(container.Parent()) && container.Parent().Parent().Parent() == declaration) { break } - container = container.Parent + container = container.Parent() } if container == nil || container == declaration { return true @@ -2013,7 +2013,7 @@ func (c *Checker) isBlockScopedNameDeclaredBeforeUse(declaration *ast.Node, usag if ast.IsFunctionLike(n) && ast.GetImmediatelyInvokedFunctionExpression(n) == nil { break } - n = n.Parent + n = n.Parent() } return n != nil && n != container } @@ -2021,7 +2021,7 @@ func (c *Checker) isBlockScopedNameDeclaredBeforeUse(declaration *ast.Node, usag case ast.IsPropertyDeclaration(declaration): // still might be illegal if a self-referencing property initializer (eg private x = this.x) return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, false /*stopAtAnyPropertyDeclaration*/) - case ast.IsParameterPropertyDeclaration(declaration, declaration.Parent): + case ast.IsParameterPropertyDeclaration(declaration, declaration.Parent()): // foo = this.bar is illegal in emitStandardClassFields when bar is a parameter property return !(c.emitStandardClassFields && ast.GetContainingClass(declaration) == ast.GetContainingClass(usage) && c.isUsedInFunctionOrInstanceProperty(usage, declaration, declContainer)) } @@ -2034,7 +2034,7 @@ func (c *Checker) isBlockScopedNameDeclaredBeforeUse(declaration *ast.Node, usag // (except when emitStandardClassFields: true and the reference is to a parameter property) // 4. inside a static property initializer, a reference to a static method in the same class // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ) - if ast.IsExportSpecifier(usage.Parent) || ast.IsExportAssignment(usage.Parent) && usage.Parent.AsExportAssignment().IsExportEquals { + if ast.IsExportSpecifier(usage.Parent()) || ast.IsExportAssignment(usage.Parent()) && usage.Parent().AsExportAssignment().IsExportEquals { // export specifiers do not use the variable, they only make it available for use return true } @@ -2043,7 +2043,7 @@ func (c *Checker) isBlockScopedNameDeclaredBeforeUse(declaration *ast.Node, usag return true } if c.isUsedInFunctionOrInstanceProperty(usage, declaration, declContainer) { - if c.emitStandardClassFields && ast.GetContainingClass(declaration) != nil && (ast.IsPropertyDeclaration(declaration) || ast.IsParameterPropertyDeclaration(declaration, declaration.Parent)) { + if c.emitStandardClassFields && ast.GetContainingClass(declaration) != nil && (ast.IsPropertyDeclaration(declaration) || ast.IsParameterPropertyDeclaration(declaration, declaration.Parent())) { return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, true /*stopAtAnyPropertyDeclaration*/) } return true @@ -2063,11 +2063,11 @@ func (c *Checker) isUsedInFunctionOrInstanceProperty(usage *ast.Node, declaratio return ast.ToFindAncestorResult(declaration.Pos() < usage.Pos()) } - if current.Parent != nil && ast.IsPropertyDeclaration(current.Parent) { - propertyDeclaration := current.Parent + if current.Parent() != nil && ast.IsPropertyDeclaration(current.Parent()) { + propertyDeclaration := current.Parent() initializerOfProperty := propertyDeclaration.Initializer() == current if initializerOfProperty { - if ast.IsStatic(current.Parent) { + if ast.IsStatic(current.Parent()) { if ast.IsMethodDeclaration(declaration) { return ast.FindAncestorTrue } @@ -2075,8 +2075,8 @@ func (c *Checker) isUsedInFunctionOrInstanceProperty(usage *ast.Node, declaratio propName := declaration.Name() if ast.IsIdentifier(propName) || ast.IsPrivateIdentifier(propName) { t := c.getTypeOfSymbol(c.getSymbolOfDeclaration(declaration)) - staticBlocks := core.Filter(declaration.Parent.Members(), ast.IsClassStaticBlockDeclaration) - if c.isPropertyInitializedInStaticBlocks(propName, t, staticBlocks, declaration.Parent.Pos(), current.Pos()) { + staticBlocks := core.Filter(declaration.Parent().Members(), ast.IsClassStaticBlockDeclaration) + if c.isPropertyInitializedInStaticBlocks(propName, t, staticBlocks, declaration.Parent().Pos(), current.Pos()) { return ast.FindAncestorTrue } } @@ -2090,17 +2090,17 @@ func (c *Checker) isUsedInFunctionOrInstanceProperty(usage *ast.Node, declaratio } } - if current.Parent != nil && ast.IsDecorator(current.Parent) { - decorator := current.Parent.AsDecorator() - if decorator.Expression == current { - if ast.IsParameterDeclaration(decorator.Parent) { - if c.isUsedInFunctionOrInstanceProperty(decorator.Parent.Parent.Parent, declaration, declContainer) { + if current.Parent() != nil && ast.IsDecorator(current.Parent()) { + decorator := current.Parent().AsDecorator() + if decorator.Expression() == current { + if ast.IsParameterDeclaration(decorator.Parent()) { + if c.isUsedInFunctionOrInstanceProperty(decorator.Parent().Parent().Parent(), declaration, declContainer) { return ast.FindAncestorTrue } return ast.FindAncestorQuit } - if ast.IsMethodDeclaration(decorator.Parent) { - if c.isUsedInFunctionOrInstanceProperty(decorator.Parent.Parent, declaration, declContainer) { + if ast.IsMethodDeclaration(decorator.Parent()) { + if c.isUsedInFunctionOrInstanceProperty(decorator.Parent().Parent(), declaration, declContainer) { return ast.FindAncestorTrue } return ast.FindAncestorQuit @@ -2113,7 +2113,7 @@ func (c *Checker) isUsedInFunctionOrInstanceProperty(usage *ast.Node, declaratio } func isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration *ast.Node, usage *ast.Node, declContainer *ast.Node) bool { - switch declaration.Parent.Parent.Kind { + switch declaration.Parent().Parent().Kind { case ast.KindVariableStatement, ast.KindForStatement, ast.KindForOfStatement: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) @@ -2122,7 +2122,7 @@ func isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration *ast.Node, } } // ForIn/ForOf case - use site should not be used in expression part - grandparent := declaration.Parent.Parent + grandparent := declaration.Parent().Parent() return ast.IsForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.Expression(), declContainer) } @@ -2134,7 +2134,7 @@ func isSameScopeDescendentOf(initial *ast.Node, parent *ast.Node, stopAt *ast.No if parent == nil { return false } - for n := initial; n != nil; n = n.Parent { + for n := initial; n != nil; n = n.Parent() { if n == parent { return true } @@ -2153,17 +2153,17 @@ func isPropertyImmediatelyReferencedWithinDeclaration(declaration *ast.Node, usa } // still might be legal if usage is deferred (e.g. x: any = () => this.x) // otherwise illegal if immediately referenced within the declaration (e.g. x: any = this.x) - for node := usage; node != nil && node != declaration; node = node.Parent { + for node := usage; node != nil && node != declaration; node = node.Parent() { switch node.Kind { case ast.KindArrowFunction: return false case ast.KindPropertyDeclaration: // even when stopping at any property declaration, they need to come from the same class return stopAtAnyPropertyDeclaration && - ((ast.IsPropertyDeclaration(declaration) && node.Parent == declaration.Parent) || - (ast.IsParameterPropertyDeclaration(declaration, declaration.Parent) && node.Parent == declaration.Parent.Parent)) + ((ast.IsPropertyDeclaration(declaration) && node.Parent() == declaration.Parent()) || + (ast.IsParameterPropertyDeclaration(declaration, declaration.Parent()) && node.Parent() == declaration.Parent().Parent())) case ast.KindBlock: - switch node.Parent.Kind { + switch node.Parent().Kind { case ast.KindMethodDeclaration, ast.KindGetAccessor, ast.KindSetAccessor: return false } @@ -2297,7 +2297,7 @@ func (c *Checker) checkSourceElement(node *ast.Node) bool { func (c *Checker) checkSourceElementWorker(node *ast.Node) { for _, jsdoc := range node.EagerJSDoc(nil) { c.checkJSDocComments(jsdoc) - if tags := jsdoc.AsJSDoc().Tags; tags != nil { + if tags := jsdoc.AsJSDoc().Tags(); tags != nil { for _, tag := range tags.Nodes { c.checkJSDocComments(tag) } @@ -2452,7 +2452,7 @@ func (c *Checker) checkSourceElementUnreachable(node *ast.Node) bool { startNode := node endNode := node - parent := node.Parent + parent := node.Parent() if parent.CanHaveStatements() { statements := parent.Statements() if offset := slices.Index(statements, node); offset >= 0 { @@ -2603,7 +2603,7 @@ func (c *Checker) resolveJSDocMemberName(name *ast.Node) *ast.Symbol { return symbol } if ast.IsQualifiedName(name) { - if symbol := c.resolveJSDocMemberName(name.AsQualifiedName().Left); symbol != nil { + if symbol := c.resolveJSDocMemberName(name.AsQualifiedName().Left()); symbol != nil { var t *Type if symbol.Flags&ast.SymbolFlagsValue != 0 { proto := c.getPropertyOfType(c.getTypeOfSymbol(symbol), "prototype") @@ -2614,7 +2614,7 @@ func (c *Checker) resolveJSDocMemberName(name *ast.Node) *ast.Symbol { if t == nil { t = c.getDeclaredTypeOfSymbol(symbol) } - return c.getPropertyOfType(t, name.AsQualifiedName().Right.Text()) + return c.getPropertyOfType(t, name.AsQualifiedName().Right().Text()) } } } @@ -2648,34 +2648,34 @@ func (c *Checker) checkJSDocTypeIsInJsFile(node *ast.Node) { func (c *Checker) checkTypeParameter(node *ast.Node) { // Grammar Checking c.checkGrammarModifiers(node) - if expr := node.AsTypeParameterDeclaration().Expression; expr != nil { + if expr := node.AsTypeParameterDeclaration().Expression(); expr != nil { c.grammarErrorOnFirstToken(expr, diagnostics.Type_expected) } tpNode := node.AsTypeParameterDeclaration() - c.checkSourceElement(tpNode.Constraint) - c.checkSourceElement(tpNode.DefaultType) + c.checkSourceElement(tpNode.Constraint()) + c.checkSourceElement(tpNode.DefaultType()) typeParameter := c.getDeclaredTypeOfTypeParameter(c.getSymbolOfDeclaration(node)) // Resolve base constraint to reveal circularity errors c.getBaseConstraintOfType(typeParameter) if c.getResolvedTypeParameterDefault(typeParameter) == c.circularConstraintType { - c.error(tpNode.DefaultType, diagnostics.Type_parameter_0_has_a_circular_default, c.TypeToString(typeParameter)) + c.error(tpNode.DefaultType(), diagnostics.Type_parameter_0_has_a_circular_default, c.TypeToString(typeParameter)) } constraintType := c.getConstraintOfTypeParameter(typeParameter) defaultType := c.getDefaultFromTypeParameter(typeParameter) if constraintType != nil && defaultType != nil { - c.checkTypeAssignableTo(defaultType, c.getTypeWithThisArgument(c.instantiateType(constraintType, newSimpleTypeMapper(typeParameter, defaultType)), defaultType, false), tpNode.DefaultType, diagnostics.Type_0_does_not_satisfy_the_constraint_1) + c.checkTypeAssignableTo(defaultType, c.getTypeWithThisArgument(c.instantiateType(constraintType, newSimpleTypeMapper(typeParameter, defaultType)), defaultType, false), tpNode.DefaultType(), diagnostics.Type_0_does_not_satisfy_the_constraint_1) } c.checkTypeNameIsReserved(node.Name(), diagnostics.Type_parameter_name_cannot_be_0) c.checkNodeDeferred(node) } func (c *Checker) checkTypeParameterDeferred(node *ast.Node) { - if ast.IsInterfaceDeclaration(node.Parent) || ast.IsClassLike(node.Parent) || ast.IsTypeOrJSTypeAliasDeclaration(node.Parent) { + if ast.IsInterfaceDeclaration(node.Parent()) || ast.IsClassLike(node.Parent()) || ast.IsTypeOrJSTypeAliasDeclaration(node.Parent()) { typeParameter := c.getDeclaredTypeOfTypeParameter(c.getSymbolOfDeclaration(node)) modifiers := c.getTypeParameterModifiers(typeParameter) & (ast.ModifierFlagsIn | ast.ModifierFlagsOut) if modifiers != 0 { - symbol := c.getSymbolOfDeclaration(node.Parent) - if ast.IsTypeOrJSTypeAliasDeclaration(node.Parent) && c.getDeclaredTypeOfSymbol(symbol).objectFlags&(ObjectFlagsAnonymous|ObjectFlagsMapped) == 0 { + symbol := c.getSymbolOfDeclaration(node.Parent()) + if ast.IsTypeOrJSTypeAliasDeclaration(node.Parent()) && c.getDeclaredTypeOfSymbol(symbol).objectFlags&(ObjectFlagsAnonymous|ObjectFlagsMapped) == 0 { c.error(node, diagnostics.Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types) } else if modifiers == ast.ModifierFlagsIn || modifiers == ast.ModifierFlagsOut { if tr := c.tracer; tr != nil { @@ -2843,7 +2843,7 @@ func (c *Checker) checkMethodDeclaration(node *ast.Node) { // Grammar checking if !c.checkGrammarMethod(node) { c.checkGrammarComputedPropertyName(node.Name()) - if ast.IsMethodDeclaration(node) && node.AsMethodDeclaration().AsteriskToken != nil && ast.IsIdentifier(node.Name()) && node.Name().Text() == "constructor" { + if ast.IsMethodDeclaration(node) && node.AsMethodDeclaration().AsteriskToken() != nil && ast.IsIdentifier(node.Name()) && node.Name().Text() == "constructor" { c.error(node.Name(), diagnostics.Class_constructor_may_not_be_a_generator) } } @@ -2887,7 +2887,7 @@ func (c *Checker) checkConstructorDeclaration(node *ast.Node) { // TS 1.0 spec (April 2014): 8.3.2 // Constructors of classes with no extends clause may not contain super calls, whereas // constructors of derived classes must contain at least one super call somewhere in their function body. - containingClassDecl := node.Parent + containingClassDecl := node.Parent() if ast.GetClassExtendsHeritageElement(containingClassDecl) == nil { return } @@ -2902,7 +2902,7 @@ func (c *Checker) checkConstructorDeclaration(node *ast.Node) { // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. superCallShouldBeRootLevel := !c.emitStandardClassFields && - (core.Some(node.Parent.Members(), isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || + (core.Some(node.Parent().Members(), isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || core.Some(node.Parameters(), func(p *ast.Node) bool { return ast.HasSyntacticModifier(p, ast.ModifierFlagsParameterPropertyModifier) })) @@ -2956,8 +2956,8 @@ func isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n *ast.Node) b } func superCallIsRootLevelInConstructor(superCall *ast.Node, body *ast.Node) bool { - superCallParent := ast.WalkUpParenthesizedExpressions(superCall.Parent) - return ast.IsExpressionStatement(superCallParent) && superCallParent.Parent == body + superCallParent := ast.WalkUpParenthesizedExpressions(superCall.Parent()) + return ast.IsExpressionStatement(superCallParent) && superCallParent.Parent() == body } func nodeImmediatelyReferencesSuperOrThis(node *ast.Node) bool { @@ -2967,7 +2967,7 @@ func nodeImmediatelyReferencesSuperOrThis(node *ast.Node) bool { case ast.KindArrowFunction, ast.KindFunctionDeclaration, ast.KindFunctionExpression, ast.KindPropertyDeclaration: return false case ast.KindBlock: - switch node.Parent.Kind { + switch node.Parent().Kind { case ast.KindConstructor, ast.KindMethodDeclaration, ast.KindGetAccessor, ast.KindSetAccessor: return false } @@ -2981,7 +2981,7 @@ func (c *Checker) checkAccessorDeclaration(node *ast.Node) { c.checkGrammarComputedPropertyName(node.Name()) } name := node.Name() - if ast.IsIdentifier(name) && name.Text() == "constructor" && ast.IsClassLike(node.Parent) { + if ast.IsIdentifier(name) && name.Text() == "constructor" && ast.IsClassLike(node.Parent()) { c.error(node.Name(), diagnostics.Class_constructor_may_not_be_an_accessor) } c.checkDecorators(node) @@ -3031,16 +3031,16 @@ func (c *Checker) checkTypeReferenceNode(node *ast.Node) { c.checkGrammarTypeArguments(node, node.TypeArgumentList()) if ast.IsTypeReferenceNode(node) && node.Flags&ast.NodeFlagsJSDoc == 0 { data := node.AsTypeReferenceNode() - if data.TypeArguments != nil && data.TypeName.End() != data.TypeArguments.Pos() { + if data.TypeArguments() != nil && data.TypeName().End() != data.TypeArguments().Pos() { // If there was a token between the type name and the type arguments, check if it was a DotToken sourceFile := ast.GetSourceFileOfNode(node) - if scanner.ScanTokenAtPosition(sourceFile, data.TypeName.End()) == ast.KindDotToken { - c.grammarErrorAtPos(node, scanner.SkipTrivia(sourceFile.Text(), data.TypeName.End()), 1, diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments) + if scanner.ScanTokenAtPosition(sourceFile, data.TypeName().End()) == ast.KindDotToken { + c.grammarErrorAtPos(node, scanner.SkipTrivia(sourceFile.Text(), data.TypeName().End()), 1, diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments) } } } c.checkSourceElements(node.TypeArguments()) - if !(isConstTypeReference(node) && ast.IsAssertionExpression(node.Parent)) { + if !(isConstTypeReference(node) && ast.IsAssertionExpression(node.Parent())) { c.checkTypeReferenceOrImport(node) } } @@ -3086,17 +3086,17 @@ func (c *Checker) getDeprecatedSuggestionNode(node *ast.Node) *ast.Node { case ast.KindCallExpression, ast.KindDecorator, ast.KindNewExpression: return c.getDeprecatedSuggestionNode(node.Expression()) case ast.KindTaggedTemplateExpression: - return c.getDeprecatedSuggestionNode(node.AsTaggedTemplateExpression().Tag) + return c.getDeprecatedSuggestionNode(node.AsTaggedTemplateExpression().Tag()) case ast.KindJsxOpeningElement, ast.KindJsxSelfClosingElement: return c.getDeprecatedSuggestionNode(node.TagName()) case ast.KindElementAccessExpression: - return node.AsElementAccessExpression().ArgumentExpression + return node.AsElementAccessExpression().ArgumentExpression() case ast.KindPropertyAccessExpression: return node.Name() case ast.KindTypeReference: - typeName := node.AsTypeReferenceNode().TypeName + typeName := node.AsTypeReferenceNode().TypeName() if ast.IsQualifiedName(typeName) { - return typeName.AsQualifiedName().Right + return typeName.AsQualifiedName().Right() } } return node @@ -3117,7 +3117,7 @@ func (c *Checker) checkTypePredicate(node *ast.Node) { if typePredicate == nil { return } - parameterName := node.AsTypePredicateNode().ParameterName + parameterName := node.AsTypePredicateNode().ParameterName() if typePredicate.kind != TypePredicateKindThis && typePredicate.kind != TypePredicateKindAssertsThis { if typePredicate.parameterIndex >= 0 { if signatureHasRestParameter(signature) && int(typePredicate.parameterIndex) == len(signature.parameters)-1 { @@ -3147,7 +3147,7 @@ func (c *Checker) checkTypePredicate(node *ast.Node) { } func (c *Checker) getTypePredicateParent(node *ast.Node) *ast.SignatureDeclaration { - parent := node.Parent + parent := node.Parent() switch parent.Kind { case ast.KindArrowFunction, ast.KindCallSignature, ast.KindFunctionDeclaration, ast.KindFunctionExpression, ast.KindFunctionType, ast.KindMethodDeclaration, ast.KindMethodSignature: @@ -3277,7 +3277,7 @@ func (c *Checker) reportDuplicateMemberErrors(node *ast.Node, name string, check } func (c *Checker) checkArrayType(node *ast.Node) { - c.checkSourceElement(node.AsArrayTypeNode().ElementType) + c.checkSourceElement(node.AsArrayTypeNode().ElementType()) } func (c *Checker) checkTupleType(node *ast.Node) { @@ -3337,11 +3337,11 @@ func (c *Checker) checkConditionalType(node *ast.Node) { func (c *Checker) checkInferType(node *ast.Node) { if ast.FindAncestor(node, func(n *ast.Node) bool { - return n.Parent != nil && n.Parent.Kind == ast.KindConditionalType && n.Parent.AsConditionalTypeNode().ExtendsType == n + return n.Parent() != nil && n.Parent().Kind == ast.KindConditionalType && n.Parent().AsConditionalTypeNode().ExtendsType() == n }) == nil { c.grammarErrorOnNode(node, diagnostics.X_infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type) } - typeParameterDeclarationNode := node.AsInferTypeNode().TypeParameter + typeParameterDeclarationNode := node.AsInferTypeNode().TypeParameter() c.checkSourceElement(typeParameterDeclarationNode) symbol := c.getSymbolOfDeclaration(typeParameterDeclarationNode) if len(symbol.Declarations) > 1 { @@ -3363,7 +3363,7 @@ func (c *Checker) checkInferType(node *ast.Node) { } func (c *Checker) checkTemplateLiteralType(node *ast.Node) { - for _, span := range node.AsTemplateLiteralTypeNode().TemplateSpans.Nodes { + for _, span := range node.AsTemplateLiteralTypeNode().TemplateSpans().Nodes { c.checkSourceElement(span.Type()) t := c.getTypeFromTypeNode(span.Type()) c.checkTypeAssignableTo(t, c.templateConstraintType, span.Type(), nil) @@ -3372,8 +3372,8 @@ func (c *Checker) checkTemplateLiteralType(node *ast.Node) { } func (c *Checker) checkImportType(node *ast.Node) { - c.checkSourceElement(node.AsImportTypeNode().Argument) - if attributes := node.AsImportTypeNode().Attributes; attributes != nil { + c.checkSourceElement(node.AsImportTypeNode().Argument()) + if attributes := node.AsImportTypeNode().Attributes(); attributes != nil { importAttributes := attributes.AsImportAttributes() c.checkGrammarImportAttributeValues(importAttributes) c.getResolutionModeOverride(importAttributes, true /*reportErrors*/) @@ -3393,14 +3393,14 @@ func (c *Checker) getResolutionModeOverride(node *ast.ImportAttributes, reportEr func (c *Checker) checkNamedTupleMember(node *ast.Node) { tupleMember := node.AsNamedTupleMember() - if tupleMember.DotDotDotToken != nil && tupleMember.QuestionToken != nil { + if tupleMember.DotDotDotToken() != nil && tupleMember.QuestionToken() != nil { c.grammarErrorOnNode(node, diagnostics.A_tuple_member_cannot_be_both_optional_and_rest) } - if tupleMember.Type.Kind == ast.KindOptionalType { - c.grammarErrorOnNode(tupleMember.Type, diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type) + if tupleMember.Type().Kind == ast.KindOptionalType { + c.grammarErrorOnNode(tupleMember.Type(), diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type) } - if tupleMember.Type.Kind == ast.KindRestType { - c.grammarErrorOnNode(tupleMember.Type, diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type) + if tupleMember.Type().Kind == ast.KindRestType { + c.grammarErrorOnNode(tupleMember.Type(), diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type) } c.checkSourceElement(node.Type()) c.getTypeFromTypeNode(node) @@ -3414,19 +3414,19 @@ func (c *Checker) checkIndexedAccessType(node *ast.Node) { func (c *Checker) checkMappedType(node *ast.Node) { mappedTypeNode := node.AsMappedTypeNode() c.checkGrammarMappedType(mappedTypeNode) - c.checkSourceElement(mappedTypeNode.TypeParameter) - c.checkSourceElement(mappedTypeNode.NameType) - c.checkSourceElement(mappedTypeNode.Type) - if mappedTypeNode.Type == nil { + c.checkSourceElement(mappedTypeNode.TypeParameter()) + c.checkSourceElement(mappedTypeNode.NameType()) + c.checkSourceElement(mappedTypeNode.Type()) + if mappedTypeNode.Type() == nil { c.reportImplicitAny(node, c.anyType, WideningKindNormal) } t := c.getTypeFromMappedTypeNode(node) nameType := c.getNameTypeFromMappedType(t) if nameType != nil { - c.checkTypeAssignableTo(nameType, c.stringNumberSymbolType, mappedTypeNode.NameType, nil) + c.checkTypeAssignableTo(nameType, c.stringNumberSymbolType, mappedTypeNode.NameType(), nil) } else { constraintType := c.getConstraintTypeFromMappedType(t) - c.checkTypeAssignableTo(constraintType, c.stringNumberSymbolType, mappedTypeNode.TypeParameter.AsTypeParameterDeclaration().Constraint, nil) + c.checkTypeAssignableTo(constraintType, c.stringNumberSymbolType, mappedTypeNode.TypeParameter().AsTypeParameterDeclaration().Constraint(), nil) } } @@ -3467,10 +3467,10 @@ func (c *Checker) checkFunctionOrMethodDeclaration(node *ast.Node) { body := node.Body() c.checkSourceElement(body) c.checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, c.getReturnTypeFromAnnotation(node)) - if node.FunctionLikeData().FullSignature != nil { - c.checkSourceElement(node.FunctionLikeData().FullSignature) - if c.getContextualCallSignature(c.getTypeFromTypeNode(node.FunctionLikeData().FullSignature), node) == nil { - c.error(node.FunctionLikeData().FullSignature, diagnostics.A_JSDoc_type_tag_on_a_function_must_have_a_signature_with_the_correct_number_of_arguments) + if node.FunctionLikeData().FullSignature() != nil { + c.checkSourceElement(node.FunctionLikeData().FullSignature()) + if c.getContextualCallSignature(c.getTypeFromTypeNode(node.FunctionLikeData().FullSignature()), node) == nil { + c.error(node.FunctionLikeData().FullSignature(), diagnostics.A_JSDoc_type_tag_on_a_function_must_have_a_signature_with_the_correct_number_of_arguments) } } if node.Type() == nil { @@ -3518,7 +3518,7 @@ func (c *Checker) checkFunctionOrConstructorSymbolWorker(symbol *ast.Symbol) { // The caveat is that if some overloads are defined in lib.d.ts, we don't want to // report the errors on those. To achieve this, we will say that the implementation is // the canonical signature only if it is in the same container as the first overload - implementationSharesContainerWithFirstOverload := implementation != nil && implementation.Parent == overloads[0].Parent + implementationSharesContainerWithFirstOverload := implementation != nil && implementation.Parent() == overloads[0].Parent() if implementationSharesContainerWithFirstOverload { return implementation } @@ -3583,7 +3583,7 @@ func (c *Checker) checkFunctionOrConstructorSymbolWorker(symbol *ast.Symbol) { } seen := false var subsequentNode *ast.Node - node.Parent.ForEachChild(func(child *ast.Node) bool { + node.Parent().ForEachChild(func(child *ast.Node) bool { if seen { subsequentNode = child return true @@ -3633,7 +3633,7 @@ func (c *Checker) checkFunctionOrConstructorSymbolWorker(symbol *ast.Symbol) { } for _, node := range declarations { inAmbientContext := node.Flags&ast.NodeFlagsAmbient != 0 - inAmbientContextOrInterface := inAmbientContext || node.Parent != nil && (ast.IsInterfaceDeclaration(node.Parent) || ast.IsTypeLiteralNode(node.Parent)) + inAmbientContextOrInterface := inAmbientContext || node.Parent() != nil && (ast.IsInterfaceDeclaration(node.Parent()) || ast.IsTypeLiteralNode(node.Parent())) if inAmbientContextOrInterface { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -3661,7 +3661,7 @@ func (c *Checker) checkFunctionOrConstructorSymbolWorker(symbol *ast.Symbol) { } else { duplicateFunctionDeclaration = true } - } else if previousDeclaration != nil && previousDeclaration.Parent == node.Parent && previousDeclaration.End() != node.Pos() && previousDeclaration.Flags&ast.NodeFlagsReparsed == 0 { + } else if previousDeclaration != nil && previousDeclaration.Parent() == node.Parent() && previousDeclaration.End() != node.Pos() && previousDeclaration.Flags&ast.NodeFlagsReparsed == 0 { reportImplementationExpectedError(previousDeclaration) } if bodyIsPresent { @@ -3732,9 +3732,9 @@ func (c *Checker) getEffectiveDeclarationFlags(n *ast.Node, flagsToCheck ast.Mod flags := c.getCombinedModifierFlagsCached(n) // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if !ast.IsInterfaceDeclaration(n.Parent) && !ast.IsClassDeclaration(n.Parent) && !ast.IsClassExpression(n.Parent) && n.Flags&ast.NodeFlagsAmbient != 0 { + if !ast.IsInterfaceDeclaration(n.Parent()) && !ast.IsClassDeclaration(n.Parent()) && !ast.IsClassExpression(n.Parent()) && n.Flags&ast.NodeFlagsAmbient != 0 { container := getEnclosingContainer(n) - if container != nil && container.Flags&ast.NodeFlagsExportContext != 0 && flags&ast.ModifierFlagsAmbient == 0 && !(ast.IsModuleBlock(n.Parent) && ast.IsGlobalScopeAugmentation(n.Parent.Parent)) { + if container != nil && container.Flags&ast.NodeFlagsExportContext != 0 && flags&ast.ModifierFlagsAmbient == 0 && !(ast.IsModuleBlock(n.Parent()) && ast.IsGlobalScopeAugmentation(n.Parent().Parent())) { // It is nested in an ambient export context, which means it is automatically exported flags |= ast.ModifierFlagsExport } @@ -3774,8 +3774,8 @@ func (c *Checker) checkAllCodePathsInNonVoidFunctionReturnOrThrow(fn *ast.Node, hasExplicitReturn := fn.Flags&ast.NodeFlagsHasExplicitReturn != 0 errorNode := fn.Type() if errorNode == nil { - if data := fn.FunctionLikeData(); data != nil && data.FullSignature != nil { - errorNode = data.FullSignature + if data := fn.FunctionLikeData(); data != nil && data.FullSignature() != nil { + errorNode = data.FullSignature() } } if errorNode == nil { @@ -3833,12 +3833,12 @@ func (c *Checker) checkIfStatement(node *ast.Node) { c.checkGrammarStatementInAmbientContext(node) t := c.checkTruthinessExpression(node.Expression(), CheckModeNormal) data := node.AsIfStatement() - c.checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(node.Expression(), t, data.ThenStatement) - c.checkSourceElement(data.ThenStatement) - if ast.IsEmptyStatement(data.ThenStatement) { - c.error(data.ThenStatement, diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement) + c.checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(node.Expression(), t, data.ThenStatement()) + c.checkSourceElement(data.ThenStatement()) + if ast.IsEmptyStatement(data.ThenStatement()) { + c.error(data.ThenStatement(), diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement) } - c.checkSourceElement(data.ElseStatement) + c.checkSourceElement(data.ElseStatement()) } func (c *Checker) checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(condExpr *ast.Node, condType *Type, body *ast.Node) { @@ -3851,8 +3851,8 @@ func (c *Checker) checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(con func (c *Checker) checkTestingKnownTruthyTypes(condExpr *ast.Node, condType *Type, body *ast.Node) { condExpr = ast.SkipParentheses(condExpr) c.checkTestingKnownTruthyType(condExpr, condType, body) - for ast.IsBinaryExpression(condExpr) && (condExpr.AsBinaryExpression().OperatorToken.Kind == ast.KindBarBarToken || condExpr.AsBinaryExpression().OperatorToken.Kind == ast.KindQuestionQuestionToken) { - condExpr = ast.SkipParentheses(condExpr.AsBinaryExpression().Left) + for ast.IsBinaryExpression(condExpr) && (condExpr.AsBinaryExpression().OperatorToken().Kind == ast.KindBarBarToken || condExpr.AsBinaryExpression().OperatorToken().Kind == ast.KindQuestionQuestionToken) { + condExpr = ast.SkipParentheses(condExpr.AsBinaryExpression().Left()) c.checkTestingKnownTruthyType(condExpr, condType, body) } } @@ -3860,7 +3860,7 @@ func (c *Checker) checkTestingKnownTruthyTypes(condExpr *ast.Node, condType *Typ func (c *Checker) checkTestingKnownTruthyType(condExpr *ast.Node, condType *Type, body *ast.Node) { location := condExpr if ast.IsLogicalOrCoalescingBinaryExpression(condExpr) { - location = ast.SkipParentheses(condExpr.AsBinaryExpression().Right) + location = ast.SkipParentheses(condExpr.AsBinaryExpression().Right()) } if ast.IsModuleExportsAccessExpression(location) { return @@ -3906,7 +3906,7 @@ func (c *Checker) checkTestingKnownTruthyType(condExpr *ast.Node, condType *Type if testedSymbol == nil && !isPromise { return } - isUsed := testedSymbol != nil && ast.IsBinaryExpression(condExpr.Parent) && c.isSymbolUsedInBinaryExpressionChain(condExpr.Parent, testedSymbol) || + isUsed := testedSymbol != nil && ast.IsBinaryExpression(condExpr.Parent()) && c.isSymbolUsedInBinaryExpressionChain(condExpr.Parent(), testedSymbol) || testedSymbol != nil && body != nil && c.isSymbolUsedInConditionBody(condExpr, body, testedNode, testedSymbol) if !isUsed { if isPromise { @@ -3928,12 +3928,12 @@ func (c *Checker) isSymbolUsedInBinaryExpressionChain(node *ast.Node, testedSymb } return child.ForEachChild(visit) } - for ast.IsBinaryExpression(node) && node.AsBinaryExpression().OperatorToken.Kind == ast.KindAmpersandAmpersandToken { - isUsed := node.AsBinaryExpression().Right.ForEachChild(visit) + for ast.IsBinaryExpression(node) && node.AsBinaryExpression().OperatorToken().Kind == ast.KindAmpersandAmpersandToken { + isUsed := node.AsBinaryExpression().Right().ForEachChild(visit) if isUsed { return true } - node = node.Parent + node = node.Parent() } return false } @@ -3945,12 +3945,12 @@ func (c *Checker) isSymbolUsedInConditionBody(expr *ast.Node, body *ast.Node, te childSymbol := c.getSymbolAtLocation(childNode, false) if childSymbol != nil && childSymbol == testedSymbol { // If the test was a simple identifier, the above check is sufficient - if ast.IsIdentifier(expr) || ast.IsIdentifier(testedNode) && ast.IsBinaryExpression(testedNode.Parent) { + if ast.IsIdentifier(expr) || ast.IsIdentifier(testedNode) && ast.IsBinaryExpression(testedNode.Parent()) { return true } // Otherwise we need to ensure the symbol is called on the same target - testedExpression := testedNode.Parent - childExpression := childNode.Parent + testedExpression := testedNode.Parent() + childExpression := childNode.Parent() for testedExpression != nil && childExpression != nil { if ast.IsIdentifier(testedExpression) && ast.IsIdentifier(childExpression) || testedExpression.Kind == ast.KindThisKeyword && childExpression.Kind == ast.KindThisKeyword { return c.getSymbolAtLocation(testedExpression, false) == c.getSymbolAtLocation(childExpression, false) @@ -3993,20 +3993,20 @@ func (c *Checker) checkForStatement(node *ast.Node) { } } data := node.AsForStatement() - if data.Initializer != nil { - if ast.IsVariableDeclarationList(data.Initializer) { - c.checkVariableDeclarationList(data.Initializer) + if data.Initializer() != nil { + if ast.IsVariableDeclarationList(data.Initializer()) { + c.checkVariableDeclarationList(data.Initializer()) } else { - c.checkExpression(data.Initializer) + c.checkExpression(data.Initializer()) } } - if data.Condition != nil { - c.checkTruthinessExpression(data.Condition, CheckModeNormal) + if data.Condition() != nil { + c.checkTruthinessExpression(data.Condition(), CheckModeNormal) } - if data.Incrementor != nil { - c.checkExpression(data.Incrementor) + if data.Incrementor() != nil { + c.checkExpression(data.Incrementor()) } - c.checkSourceElement(data.Statement) + c.checkSourceElement(data.Statement()) if node.Locals() != nil { c.registerForUnusedIdentifiersCheck(node) } @@ -4015,24 +4015,24 @@ func (c *Checker) checkForStatement(node *ast.Node) { func (c *Checker) checkForInStatement(node *ast.Node) { data := node.AsForInOrOfStatement() c.checkGrammarForInOrForOfStatement(data) - rightType := c.getNonNullableTypeIfNeeded(c.checkExpression(data.Expression)) + rightType := c.getNonNullableTypeIfNeeded(c.checkExpression(data.Expression())) // TypeScript 1.0 spec (April 2014): 5.4 // In a 'for-in' statement of the form // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if ast.IsVariableDeclarationList(data.Initializer) { - declarations := data.Initializer.AsVariableDeclarationList().Declarations.Nodes + if ast.IsVariableDeclarationList(data.Initializer()) { + declarations := data.Initializer().AsVariableDeclarationList().Declarations().Nodes if len(declarations) != 0 && ast.IsBindingPattern(declarations[0].Name()) { c.error(declarations[0].Name(), diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern) } - c.checkVariableDeclarationList(data.Initializer) + c.checkVariableDeclarationList(data.Initializer()) } else { // In a 'for-in' statement of the form // for (Var in Expr) Statement // Var must be an expression classified as a reference of type Any or the String primitive type, // and Expr must be an expression of type Any, an object type, or a type parameter type. - varExpr := data.Initializer + varExpr := data.Initializer() leftType := c.checkExpression(varExpr) if ast.IsArrayLiteralExpression(varExpr) || ast.IsObjectLiteralExpression(varExpr) { c.error(varExpr, diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern) @@ -4046,9 +4046,9 @@ func (c *Checker) checkForInStatement(node *ast.Node) { // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved // in this case error about missing name is already reported - do not report extra one if rightType == c.neverType || !c.isTypeAssignableToKind(rightType, TypeFlagsNonPrimitive|TypeFlagsInstantiableNonPrimitive) { - c.error(data.Expression, diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, c.TypeToString(rightType)) + c.error(data.Expression(), diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, c.TypeToString(rightType)) } - c.checkSourceElement(data.Statement) + c.checkSourceElement(data.Statement()) if node.Locals() != nil { c.registerForUnusedIdentifiersCheck(node) } @@ -4063,9 +4063,9 @@ func (c *Checker) checkForOfStatement(node *ast.Node) { data := node.AsForInOrOfStatement() c.checkGrammarForInOrForOfStatement(data) container := getContainingFunctionOrClassStaticBlock(node) - if data.AwaitModifier != nil { + if data.AwaitModifier() != nil { if container != nil && ast.IsClassStaticBlockDeclaration(container) { - c.grammarErrorOnNode(data.AwaitModifier, diagnostics.X_for_await_loops_cannot_be_used_inside_a_class_static_block) + c.grammarErrorOnNode(data.AwaitModifier(), diagnostics.X_for_await_loops_cannot_be_used_inside_a_class_static_block) } else { functionFlags := ast.GetFunctionFlags(container) if functionFlags&(ast.FunctionFlagsInvalid|ast.FunctionFlagsAsync) == ast.FunctionFlagsAsync && c.languageVersion < LanguageFeatureMinimumTarget.ForAwaitOf { @@ -4078,10 +4078,10 @@ func (c *Checker) checkForOfStatement(node *ast.Node) { // via checkRightHandSideOfForOf. // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. // Then check that the RHS is assignable to it. - if ast.IsVariableDeclarationList(data.Initializer) { - c.checkVariableDeclarationList(data.Initializer) + if ast.IsVariableDeclarationList(data.Initializer()) { + c.checkVariableDeclarationList(data.Initializer()) } else { - varExpr := data.Initializer + varExpr := data.Initializer() iteratedType := c.checkRightHandSideOfForOf(node) // There may be a destructuring assignment on the left side if ast.IsArrayLiteralExpression(varExpr) || ast.IsObjectLiteralExpression(varExpr) { @@ -4097,11 +4097,11 @@ func (c *Checker) checkForOfStatement(node *ast.Node) { // because we accessed properties from anyType, or it may have led to an error inside // getElementTypeOfIterable. if iteratedType != nil { - c.checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, data.Expression, nil, nil) + c.checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, data.Expression(), nil, nil) } } } - c.checkSourceElement(data.Statement) + c.checkSourceElement(data.Statement()) if node.Locals() != nil { c.registerForUnusedIdentifiersCheck(node) } @@ -4164,8 +4164,8 @@ func (c *Checker) checkReturnExpression(container *ast.Node, unwrappedReturnType if expr != nil { unwrappedExpr := ast.SkipParentheses(expr) if ast.IsConditionalExpression(unwrappedExpr) { - whenTrue := unwrappedExpr.AsConditionalExpression().WhenTrue - whenFalse := unwrappedExpr.AsConditionalExpression().WhenFalse + whenTrue := unwrappedExpr.AsConditionalExpression().WhenTrue() + whenFalse := unwrappedExpr.AsConditionalExpression().WhenFalse() c.checkReturnExpression(container, unwrappedReturnType, node, whenTrue, c.checkExpression(whenTrue), true /*inConditionalExpression*/) c.checkReturnExpression(container, unwrappedReturnType, node, whenFalse, c.checkExpression(whenFalse), true /*inConditionalExpression*/) return @@ -4204,8 +4204,8 @@ func (c *Checker) checkSwitchStatement(node *ast.Node) { var firstDefaultClause *ast.Node hasDuplicateDefaultClause := false expressionType := c.checkExpression(node.Expression()) - caseBlock := node.AsSwitchStatement().CaseBlock - for _, clause := range caseBlock.AsCaseBlock().Clauses.Nodes { + caseBlock := node.AsSwitchStatement().CaseBlock() + for _, clause := range caseBlock.AsCaseBlock().Clauses().Nodes { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause if ast.IsDefaultClause(clause) && !hasDuplicateDefaultClause { if firstDefaultClause == nil { @@ -4236,10 +4236,10 @@ func (c *Checker) checkSwitchStatement(node *ast.Node) { func (c *Checker) checkLabeledStatement(node *ast.Node) { labeledStatement := node.AsLabeledStatement() - labelNode := labeledStatement.Label + labelNode := labeledStatement.Label() labelText := labelNode.Text() if !c.checkGrammarStatementInAmbientContext(node) { - for current := node.Parent; current != nil && !ast.IsFunctionLike(current); current = current.Parent { + for current := node.Parent(); current != nil && !ast.IsFunctionLike(current); current = current.Parent() { if ast.IsLabeledStatement(current) && current.Label().Text() == labelText { c.grammarErrorOnNode(labelNode, diagnostics.Duplicate_label_0, labelText) break @@ -4249,7 +4249,7 @@ func (c *Checker) checkLabeledStatement(node *ast.Node) { if labelNode.Flags&ast.NodeFlagsUnreachable != 0 && c.compilerOptions.AllowUnusedLabels != core.TSTrue { c.errorOrSuggestion(c.compilerOptions.AllowUnusedLabels == core.TSFalse, labelNode, diagnostics.Unused_label) } - c.checkSourceElement(labeledStatement.Statement) + c.checkSourceElement(labeledStatement.Statement()) } func (c *Checker) checkThrowStatement(node *ast.Node) { @@ -4265,17 +4265,17 @@ func (c *Checker) checkThrowStatement(node *ast.Node) { func (c *Checker) checkTryStatement(node *ast.Node) { c.checkGrammarStatementInAmbientContext(node) data := node.AsTryStatement() - c.checkBlock(data.TryBlock) - if data.CatchClause != nil { - c.checkCatchClause(data.CatchClause) + c.checkBlock(data.TryBlock()) + if data.CatchClause() != nil { + c.checkCatchClause(data.CatchClause()) } - if data.FinallyBlock != nil { - c.checkBlock(data.FinallyBlock) + if data.FinallyBlock() != nil { + c.checkBlock(data.FinallyBlock()) } } func (c *Checker) checkCatchClause(node *ast.Node) { - declaration := node.AsCatchClause().VariableDeclaration + declaration := node.AsCatchClause().VariableDeclaration() if declaration != nil { c.checkVariableLikeDeclaration(declaration) typeNode := declaration.Type() @@ -4287,7 +4287,7 @@ func (c *Checker) checkCatchClause(node *ast.Node) { } else if declaration.Initializer() != nil { c.grammarErrorOnFirstToken(declaration.Initializer(), diagnostics.Catch_clause_variable_cannot_have_an_initializer) } else { - blockLocals := node.AsCatchClause().Block.Locals() + blockLocals := node.AsCatchClause().Block().Locals() if blockLocals != nil { for caughtName := range node.Locals() { if blockLocal := blockLocals[caughtName]; blockLocal != nil && blockLocal.ValueDeclaration != nil && blockLocal.Flags&ast.SymbolFlagsBlockScopedVariable != 0 { @@ -4297,7 +4297,7 @@ func (c *Checker) checkCatchClause(node *ast.Node) { } } } - c.checkBlock(node.AsCatchClause().Block) + c.checkBlock(node.AsCatchClause().Block()) } func (c *Checker) checkBindingElement(node *ast.Node) { @@ -4327,7 +4327,7 @@ func (c *Checker) checkConstructorDeclaredProperties(node *ast.Node) { } classType := c.getDeclaredTypeOfSymbol(c.getSymbolOfDeclaration(node)) for _, property := range c.getPropertiesOfType(classType) { - if kind, constructor := c.isConstructorDeclaredThisProperty(property); kind == thisAssignmentDeclarationConstructor && constructor.Parent == node { + if kind, constructor := c.isConstructorDeclaredThisProperty(property); kind == thisAssignmentDeclarationConstructor && constructor.Parent() == node { c.getTypeOfSymbol(property) } } @@ -4442,10 +4442,10 @@ func (c *Checker) checkJSDocAugmentsTagMatchesExtends(node *ast.Node, baseTypeNo } file := ast.GetSourceFileOfNode(node) for _, j := range node.EagerJSDoc(file) { - if j.AsJSDoc().Tags == nil { + if j.AsJSDoc().Tags() == nil { continue } - for _, tag := range j.AsJSDoc().Tags.Nodes { + for _, tag := range j.AsJSDoc().Tags().Nodes { if tag.Kind != ast.KindJSDocAugmentsTag { continue } @@ -4531,7 +4531,7 @@ func (c *Checker) areTypeParametersIdentical(declarations []*ast.Node, targetPar } // If the type parameter node does not have an identical constraintNode as the resolved // type parameter at this position, we report an error. - constraintNode := source.AsTypeParameterDeclaration().Constraint + constraintNode := source.AsTypeParameterDeclaration().Constraint() targetConstraint := c.getConstraintOfTypeParameter(target) // relax check if later interface augmentation has no constraint, it's more broad and is OK to merge with // a more constrained interface (this could be generalized to a full hierarchy check, but that's maybe overkill) @@ -4540,7 +4540,7 @@ func (c *Checker) areTypeParametersIdentical(declarations []*ast.Node, targetPar } // If the type parameter node has a default and it is not identical to the default // for the type parameter at this position, we report an error. - defaultNode := source.AsTypeParameterDeclaration().DefaultType + defaultNode := source.AsTypeParameterDeclaration().DefaultType() targetDefault := c.getDefaultFromTypeParameter(target) if defaultNode != nil && targetDefault != nil && !c.isTypeIdenticalTo(c.getTypeFromTypeNode(defaultNode), targetDefault) { return false @@ -4764,7 +4764,7 @@ func (c *Checker) arePropertiesAbstractOrInterface(base *ast.Symbol, baseDeclara } func (c *Checker) isPropertyAbstractOrInterface(declaration *ast.Node, baseDeclarationFlags ast.ModifierFlags) bool { - return ast.IsInterfaceDeclaration(declaration.Parent) || + return ast.IsInterfaceDeclaration(declaration.Parent()) || baseDeclarationFlags&ast.ModifierFlagsAbstract != 0 && (!ast.IsPropertyDeclaration(declaration) || declaration.Initializer() == nil) } @@ -5068,9 +5068,9 @@ func (c *Checker) isPropertyInitializedInStaticBlocks(propName *ast.Node, propTy // static block must be within the provided range as they are evaluated in document order (unlike constructors) if staticBlock.Pos() >= startPos && staticBlock.Pos() <= endPos { reference := c.factory.NewPropertyAccessExpression(c.factory.NewKeywordExpression(ast.KindThisKeyword), nil, propName, ast.NodeFlagsNone) - reference.Expression().Parent = reference - reference.Parent = staticBlock - reference.FlowNodeData().FlowNode = staticBlock.AsClassStaticBlockDeclaration().ReturnFlowNode + reference.Expression().SetParent(reference) + reference.SetParent(staticBlock) + ast.SetFlowNode(reference, staticBlock.AsClassStaticBlockDeclaration().ReturnFlowNode) flowType := c.getFlowTypeOfReferenceEx(reference, propType, c.getOptionalType(propType, false), nil, nil) if !c.containsUndefinedType(flowType) { return true @@ -5087,9 +5087,9 @@ func (c *Checker) isPropertyInitializedInConstructor(propName *ast.Node, propTyp } else { reference = c.factory.NewPropertyAccessExpression(c.factory.NewKeywordExpression(ast.KindThisKeyword), nil, propName, ast.NodeFlagsNone) } - reference.Expression().Parent = reference - reference.Parent = constructor - reference.FlowNodeData().FlowNode = constructor.AsConstructorDeclaration().ReturnFlowNode + reference.Expression().SetParent(reference) + reference.SetParent(constructor) + ast.SetFlowNode(reference, constructor.AsConstructorDeclaration().ReturnFlowNode) flowType := c.getFlowTypeOfReferenceEx(reference, propType, c.getOptionalType(propType, false), nil, nil) return !c.containsUndefinedType(flowType) } @@ -5098,7 +5098,7 @@ func (c *Checker) checkInterfaceDeclaration(node *ast.Node) { if !c.checkGrammarModifiers(node) { c.checkGrammarInterfaceDeclaration(node.AsInterfaceDeclaration()) } - if !c.containerAllowsBlockScopedVariable(node.Parent) { + if !c.containerAllowsBlockScopedVariable(node.Parent()) { c.grammarErrorOnNode(node, diagnostics.X_0_declarations_can_only_be_declared_inside_a_block, "interface") } c.checkTypeParameters(node.TypeParameters()) @@ -5250,7 +5250,7 @@ func (c *Checker) checkModuleDeclaration(node *ast.Node) { if isGlobalAugmentation && !inAmbientContext { c.error(node.Name(), diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context) } - attributes := node.AsModuleDeclaration().Attributes + attributes := node.AsModuleDeclaration().Attributes() if attributes != nil { c.checkImportAttributesType(attributes) } @@ -5296,7 +5296,7 @@ func (c *Checker) checkModuleDeclaration(node *ast.Node) { } } } - if c.compilerOptions.VerbatimModuleSyntax.IsTrue() && ast.IsSourceFile(node.Parent) && node.ModifierFlags()&ast.ModifierFlagsExport != 0 && c.program.GetEmitModuleFormatOfFile(node.Parent.AsSourceFile()) == core.ModuleKindCommonJS { + if c.compilerOptions.VerbatimModuleSyntax.IsTrue() && ast.IsSourceFile(node.Parent()) && node.ModifierFlags()&ast.ModifierFlagsExport != 0 && c.program.GetEmitModuleFormatOfFile(node.Parent().AsSourceFile()) == core.ModuleKindCommonJS { exportModifier := core.Find(node.ModifierNodes(), func(m *ast.Node) bool { return m.Kind == ast.KindExportKeyword }) c.error(exportModifier, diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled) } @@ -5317,7 +5317,7 @@ func (c *Checker) checkModuleDeclaration(node *ast.Node) { c.checkModuleAugmentationElement(statement) } } - } else if ast.IsGlobalSourceFile(node.Parent) { + } else if ast.IsGlobalSourceFile(node.Parent()) { if isGlobalAugmentation { c.error(node.Name(), diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations) } else if tspath.IsExternalModuleNameRelative(node.Name().Text()) { @@ -5361,7 +5361,7 @@ func (c *Checker) getTypeOfModuleImportAttributes(symbol *ast.Symbol) *Type { if moduleDecl == nil { result = c.emptyObjectType } else { - result = c.getTypeOfModuleDeclarationImportAttributes(moduleDecl.AsModuleDeclaration().Attributes) + result = c.getTypeOfModuleDeclarationImportAttributes(moduleDecl.AsModuleDeclaration().Attributes()) } c.moduleImportAttributesTypes[symbol] = result return result @@ -5389,7 +5389,7 @@ func (c *Checker) checkModuleAugmentationElement(node *ast.Node) { switch node.Kind { case ast.KindVariableStatement: // error each individual name in variable statement instead of marking the entire variable statement - for _, decl := range node.AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes { + for _, decl := range node.AsVariableStatement().DeclarationList().AsVariableDeclarationList().Declarations().Nodes { c.checkModuleAugmentationElement(decl) } case ast.KindExportAssignment, ast.KindExportDeclaration: @@ -5439,7 +5439,7 @@ func (c *Checker) checkImportDeclaration(node *ast.ImportDeclarationNode) { c.checkImportBinding(importClause) } var needsImportStar bool - namedBindings := importClause.AsImportClause().NamedBindings + namedBindings := importClause.AsImportClause().NamedBindings() if namedBindings != nil { if ast.IsNamespaceImport(namedBindings) { c.checkImportBinding(namedBindings) @@ -5492,8 +5492,8 @@ func (c *Checker) checkExternalImportOrExportDeclaration(node *ast.Node) bool { c.error(moduleName, diagnostics.String_literal_expected) return false } - inAmbientExternalModule := ast.IsModuleBlock(node.Parent) && ast.IsAmbientModule(node.Parent.Parent) - if !ast.IsSourceFile(node.Parent) && !inAmbientExternalModule { + inAmbientExternalModule := ast.IsModuleBlock(node.Parent()) && ast.IsAmbientModule(node.Parent().Parent()) + if !ast.IsSourceFile(node.Parent()) && !inAmbientExternalModule { c.error(moduleName, core.IfElse(ast.IsExportDeclaration(node), diagnostics.Export_declarations_are_not_permitted_in_a_namespace, diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module)) return false } @@ -5546,9 +5546,9 @@ func (c *Checker) checkModuleExportName(name *ast.Node, allowStringLiteral bool) } func hasTypeJsonImportAttribute(node *ast.Node) bool { - attributes := node.AsImportDeclaration().Attributes - return attributes != nil && core.Some(attributes.AsImportAttributes().Attributes.Nodes, func(attr *ast.Node) bool { - return attr.Name().Text() == "type" && ast.IsStringLiteralLike(attr.AsImportAttribute().Value) && attr.AsImportAttribute().Value.Text() == "json" + attributes := node.AsImportDeclaration().Attributes() + return attributes != nil && core.Some(attributes.AsImportAttributes().Attributes().Nodes, func(attr *ast.Node) bool { + return attr.Name().Text() == "type" && ast.IsStringLiteralLike(attr.AsImportAttribute().Value()) && attr.AsImportAttribute().Value().Text() == "json" }) } @@ -5599,9 +5599,9 @@ func (c *Checker) checkImportAttributesExpression(node *ast.Node) *Type { if links.resolvedType == nil { symbol := c.newSymbol(ast.SymbolFlagsObjectLiteral, ast.InternalSymbolNameImportAttributes) members := make(ast.SymbolTable) - for _, attribute := range node.AsImportAttributes().Attributes.Nodes { + for _, attribute := range node.AsImportAttributes().Attributes().Nodes { member := c.newSymbol(ast.SymbolFlagsProperty, attribute.Name().Text()) - c.valueSymbolLinks.Get(member).resolvedType = c.getRegularTypeOfLiteralType(c.checkExpressionCached(attribute.AsImportAttribute().Value)) + c.valueSymbolLinks.Get(member).resolvedType = c.getRegularTypeOfLiteralType(c.checkExpressionCached(attribute.AsImportAttribute().Value())) members[member.Name] = member } t := c.newAnonymousType(symbol, members, nil, nil, nil) @@ -5612,12 +5612,12 @@ func (c *Checker) checkImportAttributesExpression(node *ast.Node) *Type { } func (c *Checker) getImportAttributesTypeForModuleSpecifier(moduleSpecifier *ast.Node) *Type { - parent := moduleSpecifier.Parent + parent := moduleSpecifier.Parent() switch { case ast.IsImportDeclarationOrJSImportDeclaration(parent) || ast.IsExportDeclaration(parent): return c.getTypeFromImportAttributes(ast.GetImportAttributes(parent)) - case ast.IsLiteralTypeNode(parent) && ast.IsLiteralImportTypeNode(parent.Parent): - return c.getTypeFromImportAttributes(ast.GetImportAttributes(parent.Parent)) + case ast.IsLiteralTypeNode(parent) && ast.IsLiteralImportTypeNode(parent.Parent()): + return c.getTypeFromImportAttributes(ast.GetImportAttributes(parent.Parent())) case ast.IsImportCall(parent) && len(parent.Arguments()) > 1: options := parent.Arguments()[1] return c.getTypeOfPropertyOfType(c.checkExpressionCached(options), "with") @@ -5640,7 +5640,7 @@ func (c *Checker) checkImportEqualsDeclaration(node *ast.Node) { if ast.IsInternalModuleImportEqualsDeclaration(node) || c.checkExternalImportOrExportDeclaration(node) { c.checkImportBinding(node) c.markLinkedReferences(node, ReferenceHintExportImportEquals, nil, nil) - moduleReference := node.AsImportEqualsDeclaration().ModuleReference + moduleReference := node.AsImportEqualsDeclaration().ModuleReference() if !ast.IsExternalModuleReference(moduleReference) { target := c.resolveAlias(c.getSymbolOfDeclaration(node)) if target != c.unknownSymbol { @@ -5681,30 +5681,30 @@ func (c *Checker) checkExportDeclaration(node *ast.ExportDeclarationNode) { c.grammarErrorOnFirstToken(node, diagnostics.An_export_declaration_cannot_have_modifiers) } c.checkGrammarExportDeclaration(exportDecl) - if exportDecl.ModuleSpecifier == nil || c.checkExternalImportOrExportDeclaration(node) { - if exportDecl.ExportClause != nil && !ast.IsNamespaceExport(exportDecl.ExportClause) { + if exportDecl.ModuleSpecifier() == nil || c.checkExternalImportOrExportDeclaration(node) { + if exportDecl.ExportClause() != nil && !ast.IsNamespaceExport(exportDecl.ExportClause()) { // export { x, y } // export { x, y } from "foo" - for _, binding := range exportDecl.ExportClause.Elements() { + for _, binding := range exportDecl.ExportClause().Elements() { c.checkExportSpecifier(binding) } - inAmbientExternalModule := ast.IsModuleBlock(node.Parent) && ast.IsAmbientModule(node.Parent.Parent) - inAmbientNamespaceDeclaration := !inAmbientExternalModule && ast.IsModuleBlock(node.Parent) && exportDecl.ModuleSpecifier == nil && node.Flags&ast.NodeFlagsAmbient != 0 - if !ast.IsSourceFile(node.Parent) && !inAmbientExternalModule && !inAmbientNamespaceDeclaration { + inAmbientExternalModule := ast.IsModuleBlock(node.Parent()) && ast.IsAmbientModule(node.Parent().Parent()) + inAmbientNamespaceDeclaration := !inAmbientExternalModule && ast.IsModuleBlock(node.Parent()) && exportDecl.ModuleSpecifier() == nil && node.Flags&ast.NodeFlagsAmbient != 0 + if !ast.IsSourceFile(node.Parent()) && !inAmbientExternalModule && !inAmbientNamespaceDeclaration { c.error(node, diagnostics.Export_declarations_are_not_permitted_in_a_namespace) } } else { // export * from "foo" // export * as ns from "foo"; - moduleSymbol := c.resolveExternalModuleName(node, exportDecl.ModuleSpecifier, false, c.getTypeFromImportAttributes(ast.GetImportAttributes(node))) + moduleSymbol := c.resolveExternalModuleName(node, exportDecl.ModuleSpecifier(), false, c.getTypeFromImportAttributes(ast.GetImportAttributes(node))) if moduleSymbol != nil && hasExportAssignmentSymbol(moduleSymbol) { - c.error(exportDecl.ModuleSpecifier, diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, c.symbolToString(moduleSymbol)) - } else if exportDecl.ExportClause != nil { - c.checkAliasSymbol(exportDecl.ExportClause) - c.checkModuleExportName(exportDecl.ExportClause.Name(), true /*allowStringLiteral*/) + c.error(exportDecl.ModuleSpecifier(), diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, c.symbolToString(moduleSymbol)) + } else if exportDecl.ExportClause() != nil { + c.checkAliasSymbol(exportDecl.ExportClause()) + c.checkModuleExportName(exportDecl.ExportClause().Name(), true /*allowStringLiteral*/) } if c.program.GetEmitModuleFormatOfFile(ast.GetSourceFileOfNode(node)) == core.ModuleKindCommonJS { - if node.AsExportDeclaration().ExportClause != nil { + if node.AsExportDeclaration().ExportClause() != nil { // export * as ns from "foo"; c.checkExternalEmitHelpers(node, ExternalEmitHelpersImportStar) } else { @@ -5733,7 +5733,7 @@ func (c *Checker) checkExternalModuleNameInGlobalScope(node *ast.Node) { func (c *Checker) checkExportSpecifier(node *ast.ExportSpecifierNode) { c.checkAliasSymbol(node) - hasModuleSpecifier := node.Parent.Parent.ModuleSpecifier() != nil + hasModuleSpecifier := node.Parent().Parent().ModuleSpecifier() != nil c.checkModuleExportName(node.PropertyName(), hasModuleSpecifier) c.checkModuleExportName(node.Name(), true /*allowStringLiteral*/) @@ -5756,9 +5756,9 @@ func (c *Checker) checkExportSpecifier(node *ast.ExportSpecifierNode) { } func isContainedByNamespace(node *ast.Node) bool { - container := node.Parent + container := node.Parent() if !ast.IsSourceFile(container) { - container = container.Parent + container = container.Parent() } return ast.IsModuleDeclaration(container) && !ast.IsAmbientModule(container) } @@ -5837,9 +5837,9 @@ func (c *Checker) checkExportAssignment(node *ast.Node) { if isIllegalExportDefaultInCJS { c.error(node, getVerbatimModuleSyntaxErrorMessage(node)) } - container := node.Parent + container := node.Parent() if !ast.IsSourceFile(container) { - container = container.Parent + container = container.Parent() } c.checkExternalModuleExports(container) if typeNode := node.Type(); typeNode != nil && node.Kind == ast.KindExportAssignment { @@ -5946,7 +5946,7 @@ func (c *Checker) checkMissingDeclaration(node *ast.Node) { func (c *Checker) checkVariableStatement(node *ast.Node) { varStatement := node.AsVariableStatement() - declarationList := varStatement.DeclarationList + declarationList := varStatement.DeclarationList() if !c.checkGrammarModifiers(node) && !c.checkGrammarVariableDeclarationList(declarationList.AsVariableDeclarationList()) { c.checkGrammarForDisallowedBlockScopedVariableStatement(varStatement) } @@ -5958,7 +5958,7 @@ func (c *Checker) checkVariableDeclarationList(node *ast.Node) { if (blockScopeKind == ast.NodeFlagsUsing || blockScopeKind == ast.NodeFlagsAwaitUsing) && c.languageVersion < LanguageFeatureMinimumTarget.UsingAndAwaitUsing { c.checkExternalEmitHelpers(node, ExternalEmitHelpersAddDisposableResourceAndDisposeResources) } - c.checkSourceElements(node.AsVariableDeclarationList().Declarations.Nodes) + c.checkSourceElements(node.AsVariableDeclarationList().Declarations().Nodes) } func (c *Checker) checkVariableDeclaration(node *ast.Node) { @@ -6006,7 +6006,7 @@ func (c *Checker) checkVariableLikeDeclaration(node *ast.Node) { c.renamedBindingElementsInTypes = append(c.renamedBindingElementsInTypes, node) return } - if ast.IsObjectBindingPattern(node.Parent) && hasDotDotDotToken(node) && c.languageVersion < LanguageFeatureMinimumTarget.ObjectSpreadRest { + if ast.IsObjectBindingPattern(node.Parent()) && hasDotDotDotToken(node) && c.languageVersion < LanguageFeatureMinimumTarget.ObjectSpreadRest { c.checkExternalEmitHelpers(node, ExternalEmitHelpersRest) } // check computed properties inside property names of binding elements @@ -6014,7 +6014,7 @@ func (c *Checker) checkVariableLikeDeclaration(node *ast.Node) { c.checkComputedPropertyName(propName) } // check private/protected variable access - parent := node.Parent.Parent + parent := node.Parent().Parent() parentCheckMode := core.IfElse(hasDotDotDotToken(node), CheckModeRestBindingElement, CheckModeNormal) parentType := c.getTypeForBindingElementParent(parent, parentCheckMode) propNameName := node.PropertyNameOrName() @@ -6045,7 +6045,7 @@ func (c *Checker) checkVariableLikeDeclaration(node *ast.Node) { if isInAmbientOrTypeNode(node) { return } - needCheckInitializer := initializer != nil && node.Parent.Parent.Kind != ast.KindForInStatement + needCheckInitializer := initializer != nil && node.Parent().Parent().Kind != ast.KindForInStatement 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 @@ -6082,7 +6082,7 @@ func (c *Checker) checkVariableLikeDeclaration(node *ast.Node) { if node == symbol.ValueDeclaration { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error - if initializer != nil && !ast.IsForInStatement(node.Parent.Parent) { + if initializer != nil && !ast.IsForInStatement(node.Parent().Parent()) { initializerType := c.checkExpressionCached(initializer) c.checkTypeAssignableToAndOptionallyElaborate(initializerType, t, node, initializer, nil /*headMessage*/, nil) blockScopeKind := c.getCombinedNodeFlagsCached(node) & ast.NodeFlagsBlockScoped @@ -6198,12 +6198,12 @@ func (c *Checker) checkVarDeclaredNamesNotShadowed(node *ast.Node) { if c.getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol)&ast.NodeFlagsBlockScoped != 0 { varDeclList := ast.FindAncestorKind(localDeclarationSymbol.ValueDeclaration, ast.KindVariableDeclarationList) var container *ast.Node - if ast.IsVariableStatement(varDeclList.Parent) && varDeclList.Parent.Parent != nil { - container = varDeclList.Parent.Parent + if ast.IsVariableStatement(varDeclList.Parent()) && varDeclList.Parent().Parent() != nil { + container = varDeclList.Parent().Parent() } // names of block-scoped and function scoped variables can collide only // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) - namesShareScope := container != nil && (ast.IsBlock(container) && ast.IsFunctionLike(container.Parent) || + namesShareScope := container != nil && (ast.IsBlock(container) && ast.IsFunctionLike(container.Parent()) || ast.IsModuleBlock(container) || ast.IsModuleDeclaration(container) || ast.IsSourceFile(container)) // here we know that function scoped variable is "shadowed" by block scoped one // a var declaration can't hoist past a lexical declaration and it results in a SyntaxError at runtime @@ -6219,7 +6219,7 @@ func (c *Checker) checkVarDeclaredNamesNotShadowed(node *ast.Node) { func (c *Checker) checkDecorators(node *ast.Node) { // skip this check for nodes that cannot have decorators. These should have already had an error reported by // checkGrammarModifiers. - if !ast.CanHaveDecorators(node) || !ast.HasDecorators(node) || !ast.NodeCanBeDecorated(c.legacyDecorators, node, node.Parent, node.Parent.Parent) { + if !ast.CanHaveDecorators(node) || !ast.HasDecorators(node) || !ast.NodeCanBeDecorated(c.legacyDecorators, node, node.Parent(), node.Parent().Parent()) { return } firstDecorator := core.Find(node.ModifierNodes(), ast.IsDecorator) @@ -6270,7 +6270,7 @@ func (c *Checker) checkDecorator(node *ast.Node) { } var headMessage *diagnostics.Message expectedReturnType := decoratorSignature.resolvedReturnType - switch node.Parent.Kind { + switch node.Parent().Kind { case ast.KindClassDeclaration, ast.KindClassExpression: headMessage = diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1 case ast.KindPropertyDeclaration: @@ -6901,8 +6901,8 @@ func (c *Checker) reportTypeNotIterableError(errorNode *ast.Node, t *Type, allow message = diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator } suggestAwait := c.getAwaitedTypeOfPromise(t) != nil || (!allowAsyncIterables && - ast.IsForOfStatement(errorNode.Parent) && - errorNode.Parent.Expression() == errorNode && + ast.IsForOfStatement(errorNode.Parent()) && + errorNode.Parent().Expression() == errorNode && c.getGlobalAsyncIterableType() != c.emptyGenericType && c.isTypeAssignableTo(t, c.createTypeFromGenericGlobalType(c.getGlobalAsyncIterableType(), []*Type{c.anyType, c.anyType, c.anyType}))) return c.errorAndMaybeSuggestAwait(errorNode, suggestAwait, message, c.TypeToString(t)) @@ -7076,7 +7076,7 @@ func (c *Checker) checkTypeAliasDeclaration(node *ast.Node) { // Grammar checking c.checkGrammarModifiers(node) c.checkTypeNameIsReserved(node.Name(), diagnostics.Type_alias_name_cannot_be_0) - if !c.containerAllowsBlockScopedVariable(node.Parent) { + if !c.containerAllowsBlockScopedVariable(node.Parent()) { c.grammarErrorOnNode(node, diagnostics.X_0_declarations_can_only_be_declared_inside_a_block, "type") } c.checkExportsOnMergedDeclarations(node) @@ -7174,7 +7174,7 @@ func (c *Checker) getDeclarationSpaces(node *ast.Declaration) DeclarationSpaces if ast.IsExportAssignment(node) { expression = node.Expression() } else { - expression = node.AsBinaryExpression().Right + expression = node.AsBinaryExpression().Right() } // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values. if !ast.IsEntityNameExpression(expression) || c.getSymbolOfDeclaration(node).Flags&ast.SymbolFlagsAlias == 0 { @@ -7201,7 +7201,7 @@ func (c *Checker) checkTypeParameters(typeParameterDeclarations []*ast.Node) { seenDefault := false for i, node := range typeParameterDeclarations { c.checkTypeParameter(node) - defaultTypeNode := node.AsTypeParameterDeclaration().DefaultType + defaultTypeNode := node.AsTypeParameterDeclaration().DefaultType() if defaultTypeNode != nil { seenDefault = true c.checkTypeParametersNotReferenced(defaultTypeNode, typeParameterDeclarations, i) @@ -7281,7 +7281,7 @@ const ( func (c *Checker) reportUnusedVariable(location *ast.Node, diagnostic *ast.Diagnostic) { for ast.IsBindingElement(location) || ast.IsBindingPattern(location) { - location = location.Parent + location = location.Parent() } c.reportUnused(location, core.IfElse(ast.IsParameterDeclaration(location), UnusedKindParameter, UnusedKindLocal), diagnostic) } @@ -7322,7 +7322,7 @@ func (c *Checker) checkUnusedClassMembers(node *ast.Node) { c.reportUnused(member, UnusedKindLocal, NewDiagnosticForNode(member.Name(), diagnostics.X_0_is_declared_but_its_value_is_never_read, c.symbolToString(symbol))) } case ast.KindConstructor: - for _, parameter := range member.AsConstructorDeclaration().Parameters.Nodes { + for _, parameter := range member.AsConstructorDeclaration().Parameters().Nodes { if !c.isReferenced(parameter.Symbol()) && ast.HasSyntacticModifier(parameter, ast.ModifierFlagsPrivate) { c.reportUnused(parameter, UnusedKindLocal, NewDiagnosticForNode(parameter.Name(), diagnostics.Property_0_is_declared_but_its_value_is_never_read, ast.SymbolName(parameter.Symbol()))) } @@ -7348,7 +7348,7 @@ func (c *Checker) checkUnusedLocalsAndParameters(node *ast.Node) { for _, declaration := range local.Declarations { switch { case ast.IsVariableDeclaration(declaration) || ast.IsParameterDeclaration(declaration) || ast.IsBindingElement(declaration): - variableParents.Add(ast.GetRootDeclaration(declaration).Parent) + variableParents.Add(ast.GetRootDeclaration(declaration).Parent()) case ast.IsImportClause(declaration) || ast.IsImportSpecifier(declaration) || ast.IsNamespaceImport(declaration): if !isIdentifierThatStartsWithUnderscore(declaration.Name()) { if importClauses == nil { @@ -7382,7 +7382,7 @@ func (c *Checker) reportUnusedLocal(node *ast.Node, name string) { } func (c *Checker) reportUnusedVariables(node *ast.Node) { - declarations := node.AsVariableDeclarationList().Declarations.Nodes + declarations := node.AsVariableDeclarationList().Declarations().Nodes if len(declarations) > 1 && core.Every(declarations, c.isUnreferencedVariableDeclaration) { c.reportUnusedVariable(node, NewDiagnosticForNode(node, diagnostics.All_variables_are_unused)) } else { @@ -7406,7 +7406,7 @@ func (c *Checker) reportUnusedBindingElements(node *ast.Node) { func (c *Checker) reportUnusedVariableDeclarations(declarations []*ast.Node) { for _, declaration := range declarations { name := declaration.Name() - if name != nil && !ast.IsParameterPropertyDeclaration(declaration, declaration.Parent) && !ast.IsThisParameter(declaration) { + if name != nil && !ast.IsParameterPropertyDeclaration(declaration, declaration.Parent()) && !ast.IsThisParameter(declaration) { if ast.IsBindingPattern(name) { c.reportUnusedBindingElements(name) } else if c.isUnreferencedVariableDeclaration(declaration) { @@ -7427,16 +7427,16 @@ func (c *Checker) isUnreferencedVariableDeclaration(node *ast.Node) bool { if c.symbolReferenceLinks.Get(c.getSymbolOfDeclaration(node)).referenceKinds&ast.SymbolFlagsVariable != 0 { return false } - if ast.IsBindingElement(node) && ast.IsObjectBindingPattern(node.Parent) { + 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.Elements()) + lastElement := core.LastOrNil(node.Parent().Elements()) if node != lastElement && hasDotDotDotToken(lastElement) { return false } } if (ast.IsParameterDeclaration(node) || - ast.IsVariableDeclaration(node) && (ast.IsForInOrOfStatement(node.Parent.Parent) || c.getCombinedNodeFlagsCached(node)&ast.NodeFlagsUsing != 0) || - ast.IsBindingElement(node) && !(ast.IsObjectBindingPattern(node.Parent) && node.PropertyName() == nil)) && + ast.IsVariableDeclaration(node) && (ast.IsForInOrOfStatement(node.Parent().Parent()) || c.getCombinedNodeFlagsCached(node)&ast.NodeFlagsUsing != 0) || + ast.IsBindingElement(node) && !(ast.IsObjectBindingPattern(node.Parent()) && node.PropertyName() == nil)) && isIdentifierThatStartsWithUnderscore(name) { return false } @@ -7445,7 +7445,7 @@ func (c *Checker) isUnreferencedVariableDeclaration(node *ast.Node) bool { func (c *Checker) reportUnusedImports(node *ast.Node, unuseds []*ast.Node) { declarationCount := core.IfElse(node.Name() != nil, 1, 0) - namedBindings := node.AsImportClause().NamedBindings + namedBindings := node.AsImportClause().NamedBindings() if namedBindings != nil { if ast.IsNamespaceImport(namedBindings) { declarationCount++ @@ -7454,7 +7454,7 @@ func (c *Checker) reportUnusedImports(node *ast.Node, unuseds []*ast.Node) { } } if declarationCount > 1 && declarationCount == len(unuseds) { - c.reportUnused(node, UnusedKindLocal, NewDiagnosticForNode(node.Parent, diagnostics.All_imports_in_import_declaration_are_unused)) + c.reportUnused(node, UnusedKindLocal, NewDiagnosticForNode(node.Parent(), diagnostics.All_imports_in_import_declaration_are_unused)) } else { for _, unused := range unuseds { c.reportUnusedLocal(unused, unused.Name().Text()) @@ -7471,14 +7471,14 @@ func importClauseFromImported(node *ast.Node) *ast.Node { case ast.KindImportClause: return node case ast.KindNamespaceImport: - return node.Parent + return node.Parent() default: - return node.Parent.Parent + return node.Parent().Parent() } } func (c *Checker) checkUnusedInferTypeParameter(node *ast.Node) { - typeParameter := node.AsInferTypeNode().TypeParameter + typeParameter := node.AsInferTypeNode().TypeParameter() if c.isUnreferencedTypeParameter(typeParameter) { c.reportUnused(node, UnusedKindParameter, NewDiagnosticForNode(typeParameter.Name(), diagnostics.X_0_is_declared_but_never_used, typeParameter.Name().Text())) } @@ -7701,9 +7701,9 @@ func (c *Checker) checkExpressionWithContextualType(node *ast.Node, contextualTy } func (c *Checker) getContextNode(node *ast.Node) *ast.Node { - if ast.IsJsxAttributes(node) && !ast.IsJsxSelfClosingElement(node.Parent) { + if ast.IsJsxAttributes(node) && !ast.IsJsxSelfClosingElement(node.Parent()) { // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) - return node.Parent.Parent + return node.Parent().Parent() } return node } @@ -7773,11 +7773,11 @@ func (c *Checker) checkConstEnumAccess(node *ast.Node, t *Type) { // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - ok := ast.IsPropertyAccessExpression(node.Parent) && node.Parent.Expression() == node || - ast.IsElementAccessExpression(node.Parent) && node.Parent.Expression() == node || + ok := ast.IsPropertyAccessExpression(node.Parent()) && node.Parent().Expression() == node || + ast.IsElementAccessExpression(node.Parent()) && node.Parent().Expression() == node || ((ast.IsIdentifier(node) || ast.IsQualifiedName(node)) && isInRightSideOfImportOrExportAssignment(node) || - ast.IsTypeQueryNode(node.Parent) && node.Parent.AsTypeQueryNode().ExprName == node) || - ast.IsExportSpecifier(node.Parent) // We allow reexporting const enums + ast.IsTypeQueryNode(node.Parent()) && node.Parent().AsTypeQueryNode().ExprName() == node) || + ast.IsExportSpecifier(node.Parent()) // We allow reexporting const enums if !ok { c.error(node, diagnostics.X_const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query) } @@ -8050,7 +8050,7 @@ func (c *Checker) getSymbolForPrivateIdentifierExpression(node *ast.Node) *ast.S } func (c *Checker) checkSuperExpression(node *ast.Node) *Type { - isCallExpression := ast.IsCallExpression(node.Parent) && node.Parent.Expression() == node + isCallExpression := ast.IsCallExpression(node.Parent()) && node.Parent().Expression() == node immediateContainer := getSuperContainer(node, true /*stopOnFunctions*/) container := immediateContainer @@ -8073,7 +8073,7 @@ func (c *Checker) checkSuperExpression(node *ast.Node) *Type { // - In a static member function or static member accessor // topmost container must be something that is directly nested in the class declaration\object literal expression - if ast.IsClassLike(container.Parent) || ast.IsObjectLiteralExpression(container.Parent) { + if ast.IsClassLike(container.Parent()) || ast.IsObjectLiteralExpression(container.Parent()) { if ast.IsStatic(container) { return ast.NodeKindIs(container, ast.KindMethodDeclaration, ast.KindMethodSignature, ast.KindGetAccessor, ast.KindSetAccessor, ast.KindPropertyDeclaration, ast.KindClassStaticBlockDeclaration) } @@ -8102,7 +8102,7 @@ func (c *Checker) checkSuperExpression(node *ast.Node) *Type { c.error(node, diagnostics.X_super_cannot_be_referenced_in_a_computed_property_name) case isCallExpression: c.error(node, diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors) - case container == nil || container.Parent == nil || !(ast.IsClassLike(container.Parent) || ast.IsObjectLiteralExpression(container.Parent)): + case container == nil || container.Parent() == nil || !(ast.IsClassLike(container.Parent()) || ast.IsObjectLiteralExpression(container.Parent())): c.error(node, diagnostics.X_super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions) default: c.error(node, diagnostics.X_super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class) @@ -8112,12 +8112,12 @@ func (c *Checker) checkSuperExpression(node *ast.Node) *Type { if !isCallExpression && ast.IsConstructorDeclaration(immediateContainer) { c.checkThisBeforeSuper(node, container, diagnostics.X_super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class) } - if container.Parent.Kind == ast.KindObjectLiteralExpression { + if container.Parent().Kind == ast.KindObjectLiteralExpression { // for object literal assume that type of 'super' is 'any' return c.anyType } // at this point the only legal case for parent is ClassLikeDeclaration - classLikeDeclaration := container.Parent + classLikeDeclaration := container.Parent() if ast.GetClassExtendsHeritageElement(classLikeDeclaration) == nil { c.error(node, diagnostics.X_super_can_only_be_referenced_in_a_derived_class) return c.errorType @@ -8148,7 +8148,7 @@ func (c *Checker) checkSuperExpression(node *ast.Node) *Type { // for `super.x` or `super[x]` in a static initializer, mark all enclosing // block scope containers so that we can report potential collisions with // `Reflect`. - for current := ast.GetEnclosingBlockScopeContainer(node.Parent); current != nil; current = ast.GetEnclosingBlockScopeContainer(current) { + for current := ast.GetEnclosingBlockScopeContainer(node.Parent()); current != nil; current = ast.GetEnclosingBlockScopeContainer(current) { if !ast.IsSourceFile(current) || ast.IsExternalOrCommonJSModule(current.AsSourceFile()) { c.nodeLinks.Get(current).flags |= NodeCheckFlagsContainsSuperPropertyInStaticInitializer } @@ -8164,7 +8164,7 @@ func (c *Checker) isInConstructorArgumentInitializer(node *ast.Node, constructor if ast.IsFunctionLikeDeclaration(n) { return ast.FindAncestorQuit } - if ast.IsParameterDeclaration(n) && n.Parent == constructorDecl { + if ast.IsParameterDeclaration(n) && n.Parent() == constructorDecl { return ast.FindAncestorTrue } return ast.FindAncestorFalse @@ -8173,20 +8173,20 @@ func (c *Checker) isInConstructorArgumentInitializer(node *ast.Node, constructor func (c *Checker) checkTemplateExpression(node *ast.Node) *Type { expr := node.AsTemplateExpression() - length := len(expr.TemplateSpans.Nodes) + length := len(expr.TemplateSpans().Nodes) texts := make([]string, length+1) types := make([]*Type, length) - texts[0] = expr.Head.Text() - for i, span := range expr.TemplateSpans.Nodes { + texts[0] = expr.Head().Text() + for i, span := range expr.TemplateSpans().Nodes { t := c.checkExpression(span.Expression()) if c.maybeTypeOfKindConsideringBaseConstraint(t, TypeFlagsESSymbolLike) { c.error(span.Expression(), diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String) } - texts[i+1] = span.AsTemplateSpan().Literal.Text() + texts[i+1] = span.AsTemplateSpan().Literal().Text() types[i] = core.IfElse(c.isTypeAssignableTo(t, c.templateConstraintType), t, c.stringType) } var evaluated any - if !ast.IsTaggedTemplateExpression(node.Parent) { + if !ast.IsTaggedTemplateExpression(node.Parent()) { evaluated = c.evaluate(node, node).Value } if evaluated != nil { @@ -8199,8 +8199,8 @@ func (c *Checker) checkTemplateExpression(node *ast.Node) *Type { } func (c *Checker) isTemplateLiteralContext(node *ast.Node) bool { - parent := node.Parent - return ast.IsParenthesizedExpression(parent) && c.isTemplateLiteralContext(parent) || ast.IsElementAccessExpression(parent) && parent.AsElementAccessExpression().ArgumentExpression == node + parent := node.Parent() + return ast.IsParenthesizedExpression(parent) && c.isTemplateLiteralContext(parent) || ast.IsElementAccessExpression(parent) && parent.AsElementAccessExpression().ArgumentExpression() == node } func (c *Checker) isTemplateLiteralContextualType(t *Type) bool { @@ -8313,19 +8313,19 @@ func (c *Checker) createArrayLiteralType(t *Type) *Type { } func isSpreadIntoCallOrNew(node *ast.Node) bool { - parent := ast.WalkUpParenthesizedExpressions(node.Parent) - return ast.IsSpreadElement(parent) && ast.IsCallOrNewExpression(parent.Parent) + parent := ast.WalkUpParenthesizedExpressions(node.Parent()) + return ast.IsSpreadElement(parent) && ast.IsCallOrNewExpression(parent.Parent()) } func (c *Checker) checkQualifiedName(node *ast.Node, checkMode CheckMode) *Type { - left := node.AsQualifiedName().Left + left := node.AsQualifiedName().Left() var leftType *Type if ast.IsPartOfTypeQuery(node) && ast.IsThisIdentifier(left) { leftType = c.checkNonNullType(c.checkThisExpression(left), left) } else { leftType = c.checkNonNullExpression(left) } - return c.checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, node.AsQualifiedName().Right, checkMode, false) + return c.checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, node.AsQualifiedName().Right(), checkMode, false) } func (c *Checker) checkIndexedAccess(node *ast.Node, checkMode CheckMode) *Type { @@ -8346,7 +8346,7 @@ func (c *Checker) checkElementAccessExpression(node *ast.Node, exprType *Type, c if getAssignmentTargetKind(node) != AssignmentKindNone || c.isMethodAccessForCall(node) { objectType = c.getWidenedType(objectType) } - indexExpression := node.AsElementAccessExpression().ArgumentExpression + indexExpression := node.AsElementAccessExpression().ArgumentExpression() indexType := c.checkExpression(indexExpression) if c.isErrorType(objectType) || objectType == c.silentNeverType { return objectType @@ -8380,13 +8380,13 @@ func (c *Checker) isForInVariableForNumericPropertyNames(expr *ast.Node) bool { symbol := c.getResolvedSymbol(e) if symbol.Flags&ast.SymbolFlagsVariable != 0 { child := expr - node := expr.Parent + node := expr.Parent() for node != nil { - if ast.IsForInStatement(node) && child == node.AsForInOrOfStatement().Statement && c.getForInVariableSymbol(node) == symbol && c.hasNumericPropertyNames(c.getTypeOfExpression(node.Expression())) { + if ast.IsForInStatement(node) && child == node.AsForInOrOfStatement().Statement() && c.getForInVariableSymbol(node) == symbol && c.hasNumericPropertyNames(c.getTypeOfExpression(node.Expression())) { return true } child = node - node = node.Parent + node = node.Parent() } } } @@ -8397,7 +8397,7 @@ func (c *Checker) isForInVariableForNumericPropertyNames(expr *ast.Node) bool { func (c *Checker) getForInVariableSymbol(node *ast.Node) *ast.Symbol { initializer := node.Initializer() if ast.IsVariableDeclarationList(initializer) { - declarations := initializer.AsVariableDeclarationList().Declarations.Nodes + declarations := initializer.AsVariableDeclarationList().Declarations().Nodes if len(declarations) > 0 { variable := declarations[0] if variable != nil && !ast.IsBindingPattern(variable.Name()) { @@ -8490,7 +8490,7 @@ func (c *Checker) checkImportCallExpression(node *ast.Node) *Type { c.checkTypeAssignableTo(optionsType, c.getNullableType(importCallOptionsType, TypeFlagsUndefined), args[1], nil) } if ast.IsObjectLiteralExpression(args[1]) { - for _, prop := range args[1].AsObjectLiteralExpression().Properties.Nodes { + for _, prop := range args[1].AsObjectLiteralExpression().Properties().Nodes { if ast.IsPropertyAssignment(prop) && ast.IsIdentifier(prop.Name()) && prop.Name().Text() == "assert" { c.error(prop.Name(), diagnostics.Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert) break @@ -8551,9 +8551,9 @@ func (c *Checker) checkCallExpression(node *ast.Node, checkMode CheckMode) *Type // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property // as a fresh unique symbol literal type. if returnType.flags&TypeFlagsESSymbolLike != 0 && c.isSymbolOrSymbolForCall(node) { - return c.getESSymbolLikeTypeForNode(ast.WalkUpParenthesizedExpressions(node.Parent)) + return c.getESSymbolLikeTypeForNode(ast.WalkUpParenthesizedExpressions(node.Parent())) } - if ast.IsCallExpression(node) && node.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 { @@ -8871,19 +8871,19 @@ func (c *Checker) getConstructorAccessibilityError(node *ast.Node, signatures [] if modifiers == 0 || !ast.IsConstructorDeclaration(declaration) { continue } - declaringClassDeclaration := ast.GetClassLikeDeclarationOfSymbol(declaration.Parent.Symbol()) + declaringClassDeclaration := ast.GetClassLikeDeclarationOfSymbol(declaration.Parent().Symbol()) // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) if !c.isNodeWithinClass(node, declaringClassDeclaration) { containingClass := ast.GetContainingClass(node) if containingClass != nil && modifiers&ast.ModifierFlagsProtected != 0 { containingType := c.getTypeOfNode(containingClass) - if c.typeHasProtectedAccessibleBase(declaration.Parent.Symbol(), containingType) { + if c.typeHasProtectedAccessibleBase(declaration.Parent().Symbol(), containingType) { continue } } return &constructorAccessibilityError{ kind: modifiers, - declaringClass: c.getDeclaredTypeOfSymbol(declaration.Parent.Symbol()), + declaringClass: c.getDeclaredTypeOfSymbol(declaration.Parent().Symbol()), } } } @@ -8930,7 +8930,7 @@ func someSignature(signatures []*Signature, f func(s *Signature) bool) bool { } func (c *Checker) resolveTaggedTemplateExpression(node *ast.Node, candidatesOutArray *[]*Signature, checkMode CheckMode) *Signature { - tag := node.AsTaggedTemplateExpression().Tag + tag := node.AsTaggedTemplateExpression().Tag() tagType := c.checkExpression(tag) apparentType := c.getApparentType(tagType) if c.isErrorType(apparentType) { @@ -8943,7 +8943,7 @@ func (c *Checker) resolveTaggedTemplateExpression(node *ast.Node, candidatesOutA return c.resolveUntypedCall(node) } if len(callSignatures) == 0 { - if ast.IsArrayLiteralExpression(node.Parent) { + if ast.IsArrayLiteralExpression(node.Parent()) { c.error(tag, diagnostics.It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked) return c.resolveErrorCall(node) } @@ -8954,7 +8954,7 @@ func (c *Checker) resolveTaggedTemplateExpression(node *ast.Node, candidatesOutA } func (c *Checker) resolveDecorator(node *ast.Node, candidatesOutArray *[]*Signature, checkMode CheckMode) *Signature { - if !ast.CanHaveDecorators(node.Parent) { + if !ast.CanHaveDecorators(node.Parent()) { return c.resolveErrorCall(node) } funcType := c.checkExpression(node.Expression()) @@ -8997,7 +8997,7 @@ func (c *Checker) isPotentiallyUncalledDecorator(decorator *ast.Node, signatures // Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. func (c *Checker) getDiagnosticHeadMessageForDecoratorResolution(node *ast.Node) *diagnostics.Message { - switch node.Parent.Kind { + switch node.Parent().Kind { case ast.KindClassDeclaration, ast.KindClassExpression: return diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression case ast.KindParameter: @@ -9014,7 +9014,7 @@ func (c *Checker) resolveInstanceofExpression(node *ast.Node, candidatesOutArray // if rightType is an object type with a custom `[Symbol.hasInstance]` method, then it is potentially // valid on the right-hand side of the `instanceof` operator. This allows normal `object` types to // participate in `instanceof`, as per Step 2 of https://tc39.es/ecma262/#sec-instanceofoperator. - right := node.AsBinaryExpression().Right + right := node.AsBinaryExpression().Right() rightType := c.checkExpression(right) if !IsTypeAny(rightType) { hasInstanceMethodType := c.getSymbolHasInstanceMethodOfObjectType(rightType) @@ -9184,7 +9184,7 @@ func (c *Checker) reorderCandidates(signatures []*Signature, callChainFlags Sign var parent *ast.Node if signature.declaration != nil { symbol = c.getSymbolOfDeclaration(signature.declaration) - parent = signature.declaration.Parent + parent = signature.declaration.Parent() } if lastSymbol == nil || symbol == lastSymbol { if lastParent != nil && parent == lastParent { @@ -9337,13 +9337,13 @@ func (c *Checker) hasCorrectArity(node *ast.Node, args []*ast.Node, signature *S switch { case ast.IsTaggedTemplateExpression(node): argCount = len(args) - template := node.AsTaggedTemplateExpression().Template + template := node.AsTaggedTemplateExpression().Template() if ast.IsTemplateExpression(template) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. - lastSpan := core.LastOrNil(template.AsTemplateExpression().TemplateSpans.Nodes) + lastSpan := core.LastOrNil(template.AsTemplateExpression().TemplateSpans().Nodes) // we should always have at least one span. - callIsIncomplete = ast.NodeIsMissing(lastSpan.AsTemplateSpan().Literal) || ast.IsUnterminatedLiteral(lastSpan.AsTemplateSpan().Literal) + callIsIncomplete = ast.NodeIsMissing(lastSpan.AsTemplateSpan().Literal()) || ast.IsUnterminatedLiteral(lastSpan.AsTemplateSpan().Literal()) } else { // If the template didn't end in a backtick, or its beginning occurred right prior to EOF, // then this might actually turn out to be a TemplateHead in the future; @@ -9412,11 +9412,11 @@ func (c *Checker) getDecoratorArgumentCount(node *ast.Node, signature *Signature * Returns the argument count for a decorator node that works like a function invocation. */ func (c *Checker) getLegacyDecoratorArgumentCount(node *ast.Node, signature *Signature) int { - switch node.Parent.Kind { + switch node.Parent().Kind { case ast.KindClassDeclaration, ast.KindClassExpression: return 1 case ast.KindPropertyDeclaration: - if ast.HasAccessorModifier(node.Parent) { + if ast.HasAccessorModifier(node.Parent()) { return 3 } return 2 @@ -9565,14 +9565,14 @@ func (c *Checker) maybeAddMissingAwaitInfo(errorNode *ast.Node, source *Type, ta // Returns the `this` argument node in calls like `x.f(...)` and `x[f](...)`. `nil` otherwise. func (c *Checker) getThisArgumentOfCall(node *ast.Node) *ast.Node { if ast.IsBinaryExpression(node) { - return node.AsBinaryExpression().Right + return node.AsBinaryExpression().Right() } var expression *ast.Node switch { case ast.IsCallExpression(node): expression = node.Expression() case ast.IsTaggedTemplateExpression(node): - expression = node.AsTaggedTemplateExpression().Tag + expression = node.AsTaggedTemplateExpression().Tag() case ast.IsDecorator(node) && !c.legacyDecorators: expression = node.Expression() } @@ -9591,9 +9591,9 @@ func (c *Checker) getThisArgumentType(node *ast.Node) *Type { } thisArgumentType := c.checkExpression(node) switch { - case ast.IsOptionalChainRoot(node.Parent): + case ast.IsOptionalChainRoot(node.Parent()): return c.GetNonNullableType(thisArgumentType) - case ast.IsOptionalChain(node.Parent): + case ast.IsOptionalChain(node.Parent()): return c.removeOptionalTypeMarker(thisArgumentType) } return thisArgumentType @@ -10050,14 +10050,14 @@ func (c *Checker) isPromiseResolveArityError(node *ast.Node) bool { return false } decl := symbol.ValueDeclaration - if decl == nil || !ast.IsParameterDeclaration(decl) || !ast.IsFunctionExpressionOrArrowFunction(decl.Parent) || !ast.IsNewExpression(decl.Parent.Parent) || !ast.IsIdentifier(decl.Parent.Parent.Expression()) { + if decl == nil || !ast.IsParameterDeclaration(decl) || !ast.IsFunctionExpressionOrArrowFunction(decl.Parent()) || !ast.IsNewExpression(decl.Parent().Parent()) || !ast.IsIdentifier(decl.Parent().Parent().Expression()) { return false } globalPromiseSymbol := c.getGlobalPromiseConstructorSymbolOrNil() if globalPromiseSymbol == nil { return false } - constructorSymbol := c.getResolvedSymbol(decl.Parent.Parent.Expression()) + constructorSymbol := c.getResolvedSymbol(decl.Parent().Parent().Expression()) return constructorSymbol == globalPromiseSymbol } @@ -10128,11 +10128,11 @@ func (c *Checker) resolveUntypedCall(node *ast.Node) *Signature { } switch node.Kind { case ast.KindTaggedTemplateExpression: - c.checkExpression(node.AsTaggedTemplateExpression().Template) + c.checkExpression(node.AsTaggedTemplateExpression().Template()) case ast.KindJsxOpeningElement, ast.KindJsxSelfClosingElement: c.checkExpression(node.Attributes()) case ast.KindBinaryExpression: - c.checkExpression(node.AsBinaryExpression().Left) + c.checkExpression(node.AsBinaryExpression().Left()) case ast.KindCallExpression, ast.KindNewExpression: for _, argument := range node.Arguments() { c.checkExpression(argument) @@ -10164,7 +10164,7 @@ func (c *Checker) invocationErrorDetails(errorTarget *ast.Node, apparentType *Ty awaitedType := c.getAwaitedType(apparentType) maybeMissingAwait := awaitedType != nil && len(c.getSignaturesOfType(awaitedType, kind)) > 0 target := errorTarget - if ast.IsPropertyAccessExpression(errorTarget) && ast.IsCallExpression(errorTarget.Parent) { + if ast.IsPropertyAccessExpression(errorTarget) && ast.IsCallExpression(errorTarget.Parent()) { target = errorTarget.Name() } if apparentType.flags&TypeFlagsUnion != 0 { @@ -10201,7 +10201,7 @@ func (c *Checker) invocationErrorDetails(errorTarget *ast.Node, apparentType *Ty } headMessage := core.IfElse(isCall, diagnostics.This_expression_is_not_callable, diagnostics.This_expression_is_not_constructable) // Diagnose get accessors incorrectly called as functions - if ast.IsCallExpression(errorTarget.Parent) && len(errorTarget.Parent.Arguments()) == 0 { + if ast.IsCallExpression(errorTarget.Parent()) && len(errorTarget.Parent().Arguments()) == 0 { resolvedSymbol := c.getResolvedSymbolOrNil(errorTarget) if resolvedSymbol != nil && resolvedSymbol.Flags&ast.SymbolFlagsGetAccessor != 0 { headMessage = diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without @@ -10335,8 +10335,8 @@ func (c *Checker) checkClassExpressionDeferred(node *ast.Node) { func (c *Checker) checkFunctionExpressionOrObjectLiteralMethod(node *ast.Node, checkMode CheckMode) *Type { c.checkNodeDeferred(node) - if node.FunctionLikeData().FullSignature != nil { - c.checkSourceElement(node.FunctionLikeData().FullSignature) + if node.FunctionLikeData().FullSignature() != nil { + c.checkSourceElement(node.FunctionLikeData().FullSignature()) } if ast.IsFunctionExpression(node) { c.checkCollisionsForDeclarationName(node, node.Name()) @@ -10365,9 +10365,9 @@ func (c *Checker) checkFunctionExpressionOrObjectLiteralMethod(node *ast.Node, c if !hasGrammarError && ast.IsFunctionExpression(node) { c.checkGrammarForGenerator(node) } - if node.FunctionLikeData().FullSignature != nil { - if c.getContextualCallSignature(c.getTypeFromTypeNode(node.FunctionLikeData().FullSignature), node) == nil { - c.error(node.FunctionLikeData().FullSignature, diagnostics.A_JSDoc_type_tag_on_a_function_must_have_a_signature_with_the_correct_number_of_arguments) + if node.FunctionLikeData().FullSignature() != nil { + if c.getContextualCallSignature(c.getTypeFromTypeNode(node.FunctionLikeData().FullSignature()), node) == nil { + c.error(node.FunctionLikeData().FullSignature(), diagnostics.A_JSDoc_type_tag_on_a_function_must_have_a_signature_with_the_correct_number_of_arguments) } } c.contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode) @@ -10744,7 +10744,7 @@ func (c *Checker) needCollisionCheckForIdentifier(node *ast.Node, identifier *as } } root := ast.GetRootDeclaration(node) - if ast.IsParameterDeclaration(root) && ast.NodeIsMissing(root.Parent.Body()) { + if ast.IsParameterDeclaration(root) && ast.NodeIsMissing(root.Parent().Body()) { // just an overload - no codegen impact return false } @@ -10865,8 +10865,8 @@ func (c *Checker) checkExpressionWithTypeArguments(node *ast.Node) *Type { c.checkGrammarExpressionWithTypeArguments(node) c.checkSourceElements(node.TypeArguments()) if ast.IsExpressionWithTypeArguments(node) { - parent := ast.WalkUpParenthesizedExpressions(node.Parent) - if ast.IsBinaryExpression(parent) && parent.AsBinaryExpression().OperatorToken.Kind == ast.KindInstanceOfKeyword && isNodeDescendantOf(node, parent.AsBinaryExpression().Right) { + parent := ast.WalkUpParenthesizedExpressions(node.Parent()) + if ast.IsBinaryExpression(parent) && parent.AsBinaryExpression().OperatorToken().Kind == ast.KindInstanceOfKeyword && isNodeDescendantOf(node, parent.AsBinaryExpression().Right()) { c.error(node, diagnostics.The_right_hand_side_of_an_instanceof_expression_must_not_be_an_instantiation_expression) } } @@ -10874,11 +10874,11 @@ func (c *Checker) checkExpressionWithTypeArguments(node *ast.Node) *Type { if ast.IsExpressionWithTypeArguments(node) { exprType = c.checkExpression(node.Expression()) } else { - exprName := node.AsTypeQueryNode().ExprName + exprName := node.AsTypeQueryNode().ExprName() if ast.IsThisIdentifier(exprName) { - exprType = c.checkThisExpression(node.AsTypeQueryNode().ExprName) + exprType = c.checkThisExpression(node.AsTypeQueryNode().ExprName()) } else { - exprType = c.checkExpression(node.AsTypeQueryNode().ExprName) + exprType = c.checkExpression(node.AsTypeQueryNode().ExprName()) } } return c.getInstantiationExpressionType(exprType, node) @@ -10987,8 +10987,8 @@ func (c *Checker) checkMetaProperty(node *ast.Node) *Type { return c.checkNewTargetMetaProperty(node) case ast.KindImportKeyword: if ast.IsImportPhaseMetaProperty(node.AsNode()) { - if ast.IsCallExpression(node.Parent) { - debug.Assert(node.Parent.Expression() != node, "Trying to get the type of a phase import meta-property in its call") + if ast.IsCallExpression(node.Parent()) { + debug.Assert(node.Parent().Expression() != node, "Trying to get the type of a phase import meta-property in its call") } return c.errorType } @@ -11004,7 +11004,7 @@ func (c *Checker) checkNewTargetMetaProperty(node *ast.Node) *Type { return c.errorType } if ast.IsConstructorDeclaration(container) { - symbol := c.getSymbolOfDeclaration(container.Parent) + symbol := c.getSymbolOfDeclaration(container.Parent()) return c.getTypeOfSymbol(symbol) } symbol := c.getSymbolOfDeclaration(container) @@ -11086,38 +11086,38 @@ func (c *Checker) checkAwaitExpression(node *ast.Node) *Type { func (c *Checker) checkPrefixUnaryExpression(node *ast.Node) *Type { expr := node.AsPrefixUnaryExpression() - operandType := c.checkExpression(expr.Operand) + operandType := c.checkExpression(expr.Operand()) if operandType == c.silentNeverType { return c.silentNeverType } - switch expr.Operand.Kind { + switch expr.Operand().Kind { case ast.KindNumericLiteral: switch expr.Operator { case ast.KindMinusToken: - return c.getFreshTypeOfLiteralType(c.getNumberLiteralType(-jsnum.FromString(expr.Operand.Text()))) + return c.getFreshTypeOfLiteralType(c.getNumberLiteralType(-jsnum.FromString(expr.Operand().Text()))) case ast.KindPlusToken: - return c.getFreshTypeOfLiteralType(c.getNumberLiteralType(+jsnum.FromString(expr.Operand.Text()))) + return c.getFreshTypeOfLiteralType(c.getNumberLiteralType(+jsnum.FromString(expr.Operand().Text()))) } case ast.KindBigIntLiteral: if expr.Operator == ast.KindMinusToken { - return c.getFreshTypeOfLiteralType(c.getBigIntLiteralType(jsnum.NewPseudoBigInt(jsnum.ParsePseudoBigInt(expr.Operand.Text()), true /*negative*/))) + return c.getFreshTypeOfLiteralType(c.getBigIntLiteralType(jsnum.NewPseudoBigInt(jsnum.ParsePseudoBigInt(expr.Operand().Text()), true /*negative*/))) } } switch expr.Operator { case ast.KindPlusToken, ast.KindMinusToken, ast.KindTildeToken: - c.checkNonNullType(operandType, expr.Operand) + c.checkNonNullType(operandType, expr.Operand()) if c.maybeTypeOfKindConsideringBaseConstraint(operandType, TypeFlagsESSymbolLike) { - c.error(expr.Operand, diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, scanner.TokenToString(expr.Operator)) + c.error(expr.Operand(), diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, scanner.TokenToString(expr.Operator)) } if expr.Operator == ast.KindPlusToken { if c.maybeTypeOfKindConsideringBaseConstraint(operandType, TypeFlagsBigIntLike) { - c.error(expr.Operand, diagnostics.Operator_0_cannot_be_applied_to_type_1, scanner.TokenToString(expr.Operator), c.TypeToString(c.getBaseTypeOfLiteralType(operandType))) + c.error(expr.Operand(), diagnostics.Operator_0_cannot_be_applied_to_type_1, scanner.TokenToString(expr.Operator), c.TypeToString(c.getBaseTypeOfLiteralType(operandType))) } return c.numberType } return c.getUnaryResultType(operandType) case ast.KindExclamationToken: - c.checkTruthinessOfType(operandType, expr.Operand) + c.checkTruthinessOfType(operandType, expr.Operand()) facts := c.getTypeFacts(operandType, TypeFactsTruthy|TypeFactsFalsy) switch { case facts == TypeFactsTruthy: @@ -11128,10 +11128,10 @@ func (c *Checker) checkPrefixUnaryExpression(node *ast.Node) *Type { return c.booleanType } case ast.KindPlusPlusToken, ast.KindMinusMinusToken: - ok := c.checkArithmeticOperandType(expr.Operand, c.checkNonNullType(operandType, expr.Operand), diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type, false) + ok := c.checkArithmeticOperandType(expr.Operand(), c.checkNonNullType(operandType, expr.Operand()), diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type, false) if ok { // run check only if former checks succeeded to avoid reporting cascading errors - c.checkReferenceExpression(expr.Operand, diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access) + c.checkReferenceExpression(expr.Operand(), diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access) } return c.getUnaryResultType(operandType) } @@ -11140,14 +11140,14 @@ func (c *Checker) checkPrefixUnaryExpression(node *ast.Node) *Type { func (c *Checker) checkPostfixUnaryExpression(node *ast.Node) *Type { expr := node.AsPostfixUnaryExpression() - operandType := c.checkExpression(expr.Operand) + operandType := c.checkExpression(expr.Operand()) if operandType == c.silentNeverType { return c.silentNeverType } - ok := c.checkArithmeticOperandType(expr.Operand, c.checkNonNullType(operandType, expr.Operand), diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type, false) + ok := c.checkArithmeticOperandType(expr.Operand(), c.checkNonNullType(operandType, expr.Operand()), diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type, false) if ok { // run check only if former checks succeeded to avoid reporting cascading errors - c.checkReferenceExpression(expr.Operand, diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access) + c.checkReferenceExpression(expr.Operand(), diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access) } return c.getUnaryResultType(operandType) } @@ -11165,10 +11165,10 @@ func (c *Checker) getUnaryResultType(operandType *Type) *Type { func (c *Checker) checkConditionalExpression(node *ast.Node, checkMode CheckMode) *Type { cond := node.AsConditionalExpression() - t := c.checkTruthinessExpression(cond.Condition, checkMode) - c.checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(cond.Condition, t, cond.WhenTrue) - type1 := c.checkExpressionEx(cond.WhenTrue, checkMode) - type2 := c.checkExpressionEx(cond.WhenFalse, checkMode) + t := c.checkTruthinessExpression(cond.Condition(), checkMode) + c.checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(cond.Condition(), t, cond.WhenTrue()) + type1 := c.checkExpressionEx(cond.WhenTrue(), checkMode) + type2 := c.checkExpressionEx(cond.WhenFalse(), checkMode) return c.getUnionTypeEx([]*Type{type1, type2}, UnionReductionSubtype, nil, nil) } @@ -11201,7 +11201,7 @@ func (c *Checker) checkYieldExpression(node *ast.Node) *Type { return c.anyType } isAsync := (functionFlags & ast.FunctionFlagsAsync) != 0 - if node.AsYieldExpression().AsteriskToken != nil { + if node.AsYieldExpression().AsteriskToken() != nil { // Async generator functions prior to ES2018 require the __await, __asyncDelegator, // and __asyncValues helpers if isAsync && c.languageVersion < LanguageFeatureMinimumTarget.AsyncGenerators { @@ -11227,7 +11227,7 @@ func (c *Checker) checkYieldExpression(node *ast.Node) *Type { if returnType != nil && yieldedType != nil { c.checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureYieldType, core.OrElse(node.Expression(), node), node.Expression(), nil, nil) } - if node.AsYieldExpression().AsteriskToken != nil { + if node.AsYieldExpression().AsteriskToken() != nil { use := core.IfElse(isAsync, IterationUseAsyncYieldStar, IterationUseYieldStar) return core.OrElse(c.getIterationTypeOfIterable(use, IterationTypeKindReturn, yieldExpressionType, node.Expression()), c.anyType) } @@ -11249,7 +11249,7 @@ func (c *Checker) checkYieldExpression(node *ast.Node) *Type { func (c *Checker) getYieldedTypeOfYieldExpression(node *ast.Node, expressionType *Type, sentType *Type, isAsync bool) *Type { errorNode := core.OrElse(node.Expression(), node) - isYieldStar := node.AsYieldExpression().AsteriskToken != nil + isYieldStar := node.AsYieldExpression().AsteriskToken() != nil // A `yield*` expression effectively yields everything that its operand yields yieldedType := expressionType if isYieldStar { @@ -11299,8 +11299,8 @@ func (c *Checker) checkIdentifier(node *ast.Node, checkMode CheckMode) *Type { // If the identifier is declared in a binding pattern for which we're currently computing the implied type and the // reference occurs with the same binding pattern, return the non-inferrable any type. This for example occurs in // 'const [a, b = a + 1] = [2]' when we're computing the contextual type for the array literal '[2]'. - if declaration != nil && declaration.Kind == ast.KindBindingElement && slices.Contains(c.contextualBindingPatterns, declaration.Parent) && - ast.FindAncestor(node, func(parent *ast.Node) bool { return parent == declaration.Parent }) != nil { + if declaration != nil && declaration.Kind == ast.KindBindingElement && slices.Contains(c.contextualBindingPatterns, declaration.Parent()) && + ast.FindAncestor(node, func(parent *ast.Node) bool { return parent == declaration.Parent() }) != nil { return c.nonInferrableAnyType } t := c.getNarrowedTypeOfSymbol(localOrExportSymbol, node) @@ -11360,10 +11360,10 @@ func (c *Checker) checkIdentifier(node *ast.Node, checkMode CheckMode) *Type { declarationContainer := c.getControlFlowContainer(declaration) flowContainer := c.getControlFlowContainer(node) isOuterVariable := flowContainer != declarationContainer - isSpreadDestructuringAssignmentTarget := node.Parent != nil && node.Parent.Parent != nil && ast.IsSpreadAssignment(node.Parent) && c.isDestructuringAssignmentTarget(node.Parent.Parent) + isSpreadDestructuringAssignmentTarget := node.Parent() != nil && node.Parent().Parent() != nil && ast.IsSpreadAssignment(node.Parent()) && c.isDestructuringAssignmentTarget(node.Parent().Parent()) isModuleExports := symbol.Flags&ast.SymbolFlagsModuleExports != 0 typeIsAutomatic := t == c.autoType || t == c.autoArrayType - isAutomaticTypeInNonNull := typeIsAutomatic && node.Parent.Kind == ast.KindNonNullExpression + isAutomaticTypeInNonNull := typeIsAutomatic && node.Parent().Kind == ast.KindNonNullExpression // When the control flow originates in a function expression, arrow function, method, or accessor, and // we are referencing a closed-over const variable or parameter or mutable local variable past its last // assignment, we extend the origin of the control flow analysis to include the immediately enclosing @@ -11376,8 +11376,8 @@ func (c *Checker) checkIdentifier(node *ast.Node, checkMode CheckMode) *Type { // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - isNeverInitialized := immediateDeclaration != nil && ast.IsVariableDeclaration(immediateDeclaration) && !ast.IsForInOrOfStatement(immediateDeclaration.Parent.Parent) && - immediateDeclaration.Initializer() == nil && immediateDeclaration.AsVariableDeclaration().ExclamationToken == nil && + isNeverInitialized := immediateDeclaration != nil && ast.IsVariableDeclaration(immediateDeclaration) && !ast.IsForInOrOfStatement(immediateDeclaration.Parent().Parent()) && + immediateDeclaration.Initializer() == nil && immediateDeclaration.AsVariableDeclaration().ExclamationToken() == nil && c.isMutableLocalVariableDeclaration(immediateDeclaration) && !c.isSymbolAssignedDefinitely(symbol) assumeInitialized := isParameter || isAlias || @@ -11385,9 +11385,9 @@ func (c *Checker) checkIdentifier(node *ast.Node, checkMode CheckMode) *Type { isSpreadDestructuringAssignmentTarget || isModuleExports || c.isSameScopedBindingElement(node, declaration) || - t != c.autoType && t != c.autoArrayType && (!c.strictNullChecks || t.flags&(TypeFlagsAnyOrUnknown|TypeFlagsVoid) != 0 || IsInTypeQuery(node) || c.isInAmbientOrTypeNode(node) || node.Parent.Kind == ast.KindExportSpecifier) || - ast.IsNonNullExpression(node.Parent) || - ast.IsVariableDeclaration(declaration) && declaration.AsVariableDeclaration().ExclamationToken != nil || + t != c.autoType && t != c.autoArrayType && (!c.strictNullChecks || t.flags&(TypeFlagsAnyOrUnknown|TypeFlagsVoid) != 0 || IsInTypeQuery(node) || c.isInAmbientOrTypeNode(node) || node.Parent().Kind == ast.KindExportSpecifier) || + ast.IsNonNullExpression(node.Parent()) || + ast.IsVariableDeclaration(declaration) && declaration.AsVariableDeclaration().ExclamationToken() != nil || declaration.Flags&ast.NodeFlagsAmbient != 0 var initialType *Type switch { @@ -11646,11 +11646,11 @@ func (c *Checker) getFlowTypeOfAccessExpression(node *ast.Node, prop *ast.Symbol if c.strictPropertyInitialization && ast.IsAccessExpression(node) && node.Expression().Kind == ast.KindThisKeyword { if c.isPropertyWithoutInitializer(declaration) && !ast.IsStatic(declaration) { flowContainer := c.getControlFlowContainer(node) - if ast.IsConstructorDeclaration(flowContainer) && flowContainer.Parent == declaration.Parent && declaration.Flags&ast.NodeFlagsAmbient == 0 { + if ast.IsConstructorDeclaration(flowContainer) && flowContainer.Parent() == declaration.Parent() && declaration.Flags&ast.NodeFlagsAmbient == 0 { assumeUninitialized = true } } - } else if ast.IsBinaryExpression(declaration) && ast.IsPropertyAccessExpression(declaration.AsBinaryExpression().Left) && + } else if ast.IsBinaryExpression(declaration) && ast.IsPropertyAccessExpression(declaration.AsBinaryExpression().Left()) && c.getControlFlowContainer(node) == c.getControlFlowContainer(declaration) { assumeUninitialized = true } @@ -11669,7 +11669,7 @@ func (c *Checker) getFlowTypeOfAccessExpression(node *ast.Node, prop *ast.Symbol } func (c *Checker) getControlFlowContainer(node *ast.Node) *ast.Node { - return ast.FindAncestor(node.Parent, func(node *ast.Node) bool { + return ast.FindAncestor(node.Parent(), func(node *ast.Node) bool { return ast.IsFunctionLike(node) && ast.GetImmediatelyInvokedFunctionExpression(node) == nil || ast.IsModuleBlock(node) || ast.IsSourceFile(node) || ast.IsPropertyDeclaration(node) }) } @@ -11697,10 +11697,10 @@ func (c *Checker) getTypeOfPropertyInBaseClass(property *ast.Symbol) *Type { } func (c *Checker) isMethodAccessForCall(node *ast.Node) bool { - for ast.IsParenthesizedExpression(node.Parent) { - node = node.Parent + for ast.IsParenthesizedExpression(node.Parent()) { + node = node.Parent() } - return ast.IsCallOrNewExpression(node.Parent) && node.Parent.Expression() == node + return ast.IsCallOrNewExpression(node.Parent()) && node.Parent().Expression() == node } // Lookup the private identifier lexically. @@ -11840,7 +11840,7 @@ func (c *Checker) getSuggestedLibForNonExistentProperty(missingProperty string, func (c *Checker) getSuggestedSymbolForNonexistentProperty(name *ast.Node, containingType *Type) *ast.Symbol { props := c.getPropertiesOfType(containingType) - parent := name.Parent + parent := name.Parent() if ast.IsPropertyAccessExpression(parent) { props = core.Filter(props, func(prop *ast.Symbol) bool { return c.isValidPropertyAccessForCompletions(parent, containingType, prop) @@ -11911,11 +11911,11 @@ func (c *Checker) checkAndReportErrorForExtendingInterface(errorLocation *ast.No func (c *Checker) getEntityNameForExtendingInterface(node *ast.Node) *ast.Node { switch node.Kind { case ast.KindIdentifier, ast.KindQualifiedName, ast.KindPropertyAccessExpression: - if node.Parent != nil { - return c.getEntityNameForExtendingInterface(node.Parent) + if node.Parent() != nil { + return c.getEntityNameForExtendingInterface(node.Parent()) } case ast.KindTypeReference: - return node.AsTypeReferenceNode().TypeName + return node.AsTypeReferenceNode().TypeName() case ast.KindExpressionWithTypeArguments: if ast.IsEntityNameExpression(node.Expression()) { return node.Expression() @@ -11926,9 +11926,9 @@ func (c *Checker) getEntityNameForExtendingInterface(node *ast.Node) *ast.Node { func (c *Checker) isUncalledFunctionReference(node *ast.Node, symbol *ast.Symbol) bool { if symbol.Flags&(ast.SymbolFlagsFunction|ast.SymbolFlagsMethod) != 0 { - parent := ast.FindAncestor(node.Parent, func(n *ast.Node) bool { return !ast.IsAccessExpression(n) }) + parent := ast.FindAncestor(node.Parent(), func(n *ast.Node) bool { return !ast.IsAccessExpression(n) }) if parent == nil { - parent = node.Parent + parent = node.Parent() } if ast.IsCallLikeExpression(parent) { return ast.IsCallOrNewExpression(parent) && ast.IsIdentifier(node) && c.hasMatchingArgument(parent, node) @@ -11954,7 +11954,7 @@ func (c *Checker) checkPropertyNotUsedBeforeDeclaration(prop *ast.Symbol, node * !(ast.IsMethodDeclaration(valueDeclaration) && c.getCombinedModifierFlagsCached(valueDeclaration)&ast.ModifierFlagsStatic != 0) && (c.compilerOptions.GetUseDefineForClassFields() || !c.isPropertyDeclaredInAncestorClass(prop)) { diagnostic = c.error(right, diagnostics.Property_0_is_used_before_its_initialization, declarationName) - } else if ast.IsClassDeclaration(valueDeclaration) && !ast.IsTypeReferenceNode(node.Parent) && valueDeclaration.Flags&ast.NodeFlagsAmbient == 0 && !c.isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) { + } else if ast.IsClassDeclaration(valueDeclaration) && !ast.IsTypeReferenceNode(node.Parent()) && valueDeclaration.Flags&ast.NodeFlagsAmbient == 0 && !c.isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) { diagnostic = c.error(right, diagnostics.Class_0_used_before_its_declaration, declarationName) } if diagnostic != nil { @@ -11995,7 +11995,7 @@ func (c *Checker) checkPropertyAccessibilityEx(node *ast.Node, isSuper bool, wri case ast.KindPropertyAccessExpression: errorNode = node.AsPropertyAccessExpression().Name() case ast.KindQualifiedName: - errorNode = node.AsQualifiedName().Right + errorNode = node.AsQualifiedName().Right() case ast.KindImportType: errorNode = node case ast.KindBindingElement: @@ -12049,7 +12049,7 @@ func (c *Checker) checkPropertyAccessibilityAtLocation(location *ast.Node, isSup // Referencing abstract properties within their own constructors is not allowed if flags&ast.ModifierFlagsAbstract != 0 && c.symbolHasNonMethodDeclaration(prop) && (isThisProperty(location) || isThisInitializedObjectBindingExpression(location) || - ast.IsObjectBindingPattern(location.Parent) && isThisInitializedDeclaration(location.Parent.Parent)) { + ast.IsObjectBindingPattern(location.Parent()) && isThisInitializedDeclaration(location.Parent().Parent())) { parentSymbol := c.getParentOfSymbol(prop) if parentSymbol != nil && parentSymbol.Flags&ast.SymbolFlagsClass != 0 && c.isNodeUsedDuringClassInitialization(location) { if errorNode != nil { @@ -12290,9 +12290,9 @@ func (c *Checker) getContextualThisParameterType(fn *ast.Node) *Type { } // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. - parent := ast.WalkUpParenthesizedExpressions(fn.Parent) + parent := ast.WalkUpParenthesizedExpressions(fn.Parent()) if ast.IsAssignmentExpression(parent, false) { - target := parent.AsBinaryExpression().Left + target := parent.AsBinaryExpression().Left() if ast.IsAccessExpression(target) { expression := target.Expression() // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` @@ -12397,8 +12397,8 @@ func (c *Checker) tryGetThisTypeAtEx(node *ast.Node, includeGlobalThis bool, con return c.getFlowTypeOfReference(node, thisType) } } - if container.Parent != nil && ast.IsClassLike(container.Parent) { - symbol := c.getSymbolOfDeclaration(container.Parent) + if container.Parent() != nil && ast.IsClassLike(container.Parent()) { + symbol := c.getSymbolOfDeclaration(container.Parent()) var t *Type if ast.IsStatic(container) { t = c.getTypeOfSymbol(symbol) @@ -12422,7 +12422,7 @@ func (c *Checker) tryGetThisTypeAtEx(node *ast.Node, includeGlobalThis bool, con func (c *Checker) getThisContainer(node *ast.Node, includeArrowFunctions bool, includeClassComputedPropertyName bool) *ast.Node { for { - node = node.Parent + node = node.Parent() if node == nil { // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. panic("No parent in getThisContainer") @@ -12433,7 +12433,7 @@ func (c *Checker) getThisContainer(node *ast.Node, includeArrowFunctions bool, i // then the computed property is not a 'this' container. // A computed property name in a class needs to be a this container // so that we can error on it. - if includeClassComputedPropertyName && ast.IsClassLike(node.Parent.Parent) { + if includeClassComputedPropertyName && ast.IsClassLike(node.Parent().Parent()) { return node } // If this is a computed property, then the parent should not @@ -12441,17 +12441,17 @@ func (c *Checker) getThisContainer(node *ast.Node, includeArrowFunctions bool, i // in an object literal, like a method or accessor. But in order for // such a parent to be a this container, the reference must be in // the *body* of the container. - node = node.Parent.Parent + node = node.Parent().Parent() case ast.KindDecorator: // Decorators are always applied outside of the body of a class or method. - if node.Parent.Kind == ast.KindParameter && ast.IsClassElement(node.Parent.Parent) { + if node.Parent().Kind == ast.KindParameter && ast.IsClassElement(node.Parent().Parent()) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. - node = node.Parent.Parent - } else if ast.IsClassElement(node.Parent) { + node = node.Parent().Parent() + } else if ast.IsClassElement(node.Parent()) { // If the decorator's parent is a class element, we resolve the 'this' container // from the parent class declaration. - node = node.Parent + node = node.Parent() } case ast.KindArrowFunction: if !includeArrowFunctions { @@ -12469,18 +12469,18 @@ func (c *Checker) getThisContainer(node *ast.Node, includeArrowFunctions bool, i func (c *Checker) isInParameterInitializerBeforeContainingFunction(node *ast.Node) bool { inBindingInitializer := false - for node.Parent != nil && !ast.IsFunctionLike(node.Parent) { - if ast.IsParameterDeclaration(node.Parent) { - if inBindingInitializer || node.Parent.Initializer() == node { + for node.Parent() != nil && !ast.IsFunctionLike(node.Parent()) { + if ast.IsParameterDeclaration(node.Parent()) { + if inBindingInitializer || node.Parent().Initializer() == node { return true } } - if ast.IsBindingElement(node.Parent) && node.Parent.Initializer() == node { + if ast.IsBindingElement(node.Parent()) && node.Parent().Initializer() == node { inBindingInitializer = true } - node = node.Parent + node = node.Parent() } return false @@ -12489,14 +12489,14 @@ func (c *Checker) isInParameterInitializerBeforeContainingFunction(node *ast.Nod func (c *Checker) checkThisInStaticClassFieldInitializerInDecoratedClass(thisExpression *ast.Node, container *ast.Node) { if ast.IsPropertyDeclaration(container) && ast.HasStaticModifier(container) && c.legacyDecorators { initializer := container.Initializer() - if initializer != nil && initializer.Loc.ContainsInclusive(thisExpression.Pos()) && ast.HasDecorators(container.Parent) { + if initializer != nil && initializer.Loc.ContainsInclusive(thisExpression.Pos()) && ast.HasDecorators(container.Parent()) { c.error(thisExpression, diagnostics.Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class) } } } func (c *Checker) checkThisBeforeSuper(node *ast.Node, container *ast.Node, diagnosticMessage *diagnostics.Message) { - containingClassDecl := container.Parent + containingClassDecl := container.Parent() baseTypeNode := ast.GetClassExtendsHeritageElement(containingClassDecl) // If a containing class does not have extends clause or the class extends null // skip checking whether super statement is called before "this" accessing. @@ -12565,7 +12565,7 @@ func (c *Checker) checkAssertionDeferred(node *ast.Node) { func (c *Checker) checkBinaryExpression(node *ast.Node, checkMode CheckMode) *Type { binary := node.AsBinaryExpression() - return c.checkBinaryLikeExpression(binary.Left, binary.OperatorToken, binary.Right, checkMode, node) + return c.checkBinaryLikeExpression(binary.Left(), binary.OperatorToken(), binary.Right(), checkMode, node) } func (c *Checker) checkBinaryLikeExpression(left *ast.Node, operatorToken *ast.Node, right *ast.Node, checkMode CheckMode, errorNode *ast.Node) *Type { @@ -12576,14 +12576,14 @@ func (c *Checker) checkBinaryLikeExpression(left *ast.Node, operatorToken *ast.N leftType := c.checkExpressionEx(left, checkMode) rightType := c.checkExpressionEx(right, checkMode) if ast.IsLogicalOrCoalescingBinaryOperator(operator) { - parent := left.Parent.Parent + parent := left.Parent().Parent() for ast.IsParenthesizedExpression(parent) || ast.IsLogicalOrCoalescingBinaryExpression(parent) { - parent = parent.Parent + parent = parent.Parent() } if operator == ast.KindAmpersandAmpersandToken || ast.IsIfStatement(parent) { var body *ast.Node if ast.IsIfStatement(parent) { - body = parent.AsIfStatement().ThenStatement + body = parent.AsIfStatement().ThenStatement() } c.checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(left, leftType, body) } @@ -12641,7 +12641,7 @@ func (c *Checker) checkBinaryLikeExpression(left *ast.Node, operatorToken *ast.N rhsEval := c.evaluate(right, right) if numValue, ok := rhsEval.Value.(jsnum.Number); ok && numValue.Abs() >= 32 { // Elevate from suggestion to error within an enum member - c.errorOrSuggestion(ast.IsEnumMember(ast.WalkUpParenthesizedExpressions(right.Parent.Parent)), errorNode, diagnostics.This_operation_can_be_simplified_This_shift_is_identical_to_0_1_2, scanner.GetTextOfNode(left), scanner.TokenToString(operator), numValue.Remainder(32)) + c.errorOrSuggestion(ast.IsEnumMember(ast.WalkUpParenthesizedExpressions(right.Parent().Parent())), errorNode, diagnostics.This_operation_can_be_simplified_This_shift_is_identical_to_0_1_2, scanner.GetTextOfNode(left), scanner.TokenToString(operator), numValue.Remainder(32)) } } } @@ -12766,7 +12766,7 @@ func (c *Checker) checkBinaryLikeExpression(left *ast.Node, operatorToken *ast.N c.checkAssignmentOperator(left, operator, right, leftType, rightType) return rightType case ast.KindCommaToken: - if !c.compilerOptions.AllowUnreachableCode.IsTrue() && c.isSideEffectFree(left) && !c.isIndirectCall(left.Parent) { + if !c.compilerOptions.AllowUnreachableCode.IsTrue() && c.isSideEffectFree(left) && !c.isIndirectCall(left.Parent()) { sf := ast.GetSourceFileOfNode(left) start := scanner.SkipTrivia(sf.Text(), left.Pos()) isInDiag2657 := core.Some(sf.Diagnostics(), func(d *ast.Diagnostic) bool { @@ -12787,22 +12787,22 @@ func (c *Checker) checkBinaryLikeExpression(left *ast.Node, operatorToken *ast.N func (c *Checker) checkDestructuringAssignment(node *ast.Node, sourceType *Type, checkMode CheckMode, rightIsThis bool) *Type { var target *ast.Node if ast.IsShorthandPropertyAssignment(node) { - initializer := node.AsShorthandPropertyAssignment().ObjectAssignmentInitializer + initializer := node.AsShorthandPropertyAssignment().ObjectAssignmentInitializer() if initializer != nil { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if c.strictNullChecks && !c.hasTypeFacts(c.checkExpression(initializer), TypeFactsIsUndefined) { sourceType = c.getTypeWithFacts(sourceType, TypeFactsNEUndefined) } - c.checkBinaryLikeExpression(node.Name(), node.AsShorthandPropertyAssignment().EqualsToken, initializer, checkMode, nil) + c.checkBinaryLikeExpression(node.Name(), node.AsShorthandPropertyAssignment().EqualsToken(), initializer, checkMode, nil) } target = node.Name() } else { target = node } - if ast.IsBinaryExpression(target) && target.AsBinaryExpression().OperatorToken.Kind == ast.KindEqualsToken { + if ast.IsBinaryExpression(target) && target.AsBinaryExpression().OperatorToken().Kind == ast.KindEqualsToken { c.checkBinaryExpression(target, checkMode) - target = target.AsBinaryExpression().Left + target = target.AsBinaryExpression().Left() // A default value is specified, so remove undefined from the final type. if c.strictNullChecks { sourceType = c.getTypeWithFacts(sourceType, TypeFactsNEUndefined) @@ -12924,8 +12924,8 @@ func (c *Checker) checkArrayLiteralDestructuringElementAssignment(node *ast.Node c.error(element, diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern) } else { restExpression := element.Expression() - if ast.IsBinaryExpression(restExpression) && restExpression.AsBinaryExpression().OperatorToken.Kind == ast.KindEqualsToken { - c.error(restExpression.AsBinaryExpression().OperatorToken, diagnostics.A_rest_element_cannot_have_an_initializer) + if ast.IsBinaryExpression(restExpression) && restExpression.AsBinaryExpression().OperatorToken().Kind == ast.KindEqualsToken { + c.error(restExpression.AsBinaryExpression().OperatorToken(), diagnostics.A_rest_element_cannot_have_an_initializer) } else { c.checkGrammarForDisallowedTrailingComma(elements, diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma) var t *Type @@ -12943,10 +12943,10 @@ func (c *Checker) checkArrayLiteralDestructuringElementAssignment(node *ast.Node func (c *Checker) checkReferenceAssignment(target *ast.Node, sourceType *Type, checkMode CheckMode) *Type { targetType := c.checkExpressionEx(target, checkMode) - message := core.IfElse(ast.IsSpreadAssignment(target.Parent), + message := core.IfElse(ast.IsSpreadAssignment(target.Parent()), diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access, diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access) - optionalMessage := core.IfElse(ast.IsSpreadAssignment(target.Parent), + optionalMessage := core.IfElse(ast.IsSpreadAssignment(target.Parent()), diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access, diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access) if c.checkReferenceExpression(target, message, optionalMessage) { @@ -12997,7 +12997,7 @@ func (c *Checker) getBaseTypesIfUnrelated(leftType *Type, rightType *Type, isRel func (c *Checker) checkAssignmentOperator(left *ast.Node, operator ast.Kind, right *ast.Node, leftType *Type, rightType *Type) { if ast.IsAssignmentOperator(operator) { // We ignore assignments of undefined to CommonJS exports when there are multiple assignment declarations - if ast.IsDeclarationNode(left.Parent) && ast.GetAssignmentDeclarationKind(left.Parent) == ast.JSDeclarationKindExportsProperty { + if ast.IsDeclarationNode(left.Parent()) && ast.GetAssignmentDeclarationKind(left.Parent()) == ast.JSDeclarationKindExportsProperty { if symbol := c.symbolNodeLinks.Get(left).resolvedSymbol; symbol != nil && len(symbol.Declarations) > 1 && rightType.flags&TypeFlagsUndefined != 0 { return } @@ -13143,7 +13143,7 @@ func (c *Checker) getSyntacticTruthySemantics(node *ast.Node) PredicateSemantics } return PredicateSemanticsNever case ast.KindConditionalExpression: - return c.getSyntacticTruthySemantics(node.AsConditionalExpression().WhenTrue) | c.getSyntacticTruthySemantics(node.AsConditionalExpression().WhenFalse) + return c.getSyntacticTruthySemantics(node.AsConditionalExpression().WhenTrue()) | c.getSyntacticTruthySemantics(node.AsConditionalExpression().WhenFalse()) case ast.KindIdentifier: if c.getResolvedSymbol(node) == c.undefinedSymbol { return PredicateSemanticsNever @@ -13153,19 +13153,19 @@ func (c *Checker) getSyntacticTruthySemantics(node *ast.Node) PredicateSemantics } func (c *Checker) checkNullishCoalesceOperands(left *ast.Node, right *ast.Node) { - if ast.IsBinaryExpression(left.Parent.Parent) { - grandparentLeft := left.Parent.Parent.AsBinaryExpression().Left - grandparentOperatorToken := left.Parent.Parent.AsBinaryExpression().OperatorToken + if ast.IsBinaryExpression(left.Parent().Parent()) { + grandparentLeft := left.Parent().Parent().AsBinaryExpression().Left() + grandparentOperatorToken := left.Parent().Parent().AsBinaryExpression().OperatorToken() if ast.IsBinaryExpression(grandparentLeft) && grandparentOperatorToken.Kind == ast.KindBarBarToken { c.grammarErrorOnNode(grandparentLeft, diagnostics.X_0_and_1_operations_cannot_be_mixed_without_parentheses, scanner.TokenToString(ast.KindQuestionQuestionToken), scanner.TokenToString(grandparentOperatorToken.Kind)) } } else if ast.IsBinaryExpression(left) { - operatorToken := left.AsBinaryExpression().OperatorToken + operatorToken := left.AsBinaryExpression().OperatorToken() if operatorToken.Kind == ast.KindBarBarToken || operatorToken.Kind == ast.KindAmpersandAmpersandToken { c.grammarErrorOnNode(left, diagnostics.X_0_and_1_operations_cannot_be_mixed_without_parentheses, scanner.TokenToString(operatorToken.Kind), scanner.TokenToString(ast.KindQuestionQuestionToken)) } } else if ast.IsBinaryExpression(right) { - operatorToken := right.AsBinaryExpression().OperatorToken + operatorToken := right.AsBinaryExpression().OperatorToken() if operatorToken.Kind == ast.KindAmpersandAmpersandToken { c.grammarErrorOnNode(right, diagnostics.X_0_and_1_operations_cannot_be_mixed_without_parentheses, scanner.TokenToString(ast.KindQuestionQuestionToken), scanner.TokenToString(operatorToken.Kind)) } @@ -13201,7 +13201,7 @@ func (c *Checker) getSyntacticNullishnessSemantics(node *ast.Node) PredicateSema case ast.KindBinaryExpression: // List of operators that can produce null/undefined: // || ||= && &&= ?? ??= - switch node.AsBinaryExpression().OperatorToken.Kind { + switch node.AsBinaryExpression().OperatorToken().Kind { case ast.KindBarBarToken, ast.KindBarBarEqualsToken, ast.KindAmpersandAmpersandToken, @@ -13210,25 +13210,25 @@ func (c *Checker) getSyntacticNullishnessSemantics(node *ast.Node) PredicateSema // For these operator kinds, the right operand is effectively controlling case ast.KindCommaToken, ast.KindEqualsToken: - return c.getSyntacticNullishnessSemantics(node.AsBinaryExpression().Right) + return c.getSyntacticNullishnessSemantics(node.AsBinaryExpression().Right()) // For nullish coalescing: result is the left operand when left is non-null, // or the right operand when left is null/undefined. The nullishness of the // result combines both paths: the left's non-null path contributes Never, // and when left can be null, the right's semantics are also included. case ast.KindQuestionQuestionToken, ast.KindQuestionQuestionEqualsToken: - leftSemantics := c.getSyntacticNullishnessSemantics(node.AsBinaryExpression().Left) + leftSemantics := c.getSyntacticNullishnessSemantics(node.AsBinaryExpression().Left()) // The non-null path (left is non-null): left branch taken, result has Never bit result := leftSemantics & PredicateSemanticsNever // The null path (left is null/undefined): right branch taken, result inherits right's semantics if leftSemantics&PredicateSemanticsAlways != 0 { - result |= c.getSyntacticNullishnessSemantics(node.AsBinaryExpression().Right) + result |= c.getSyntacticNullishnessSemantics(node.AsBinaryExpression().Right()) } return result } return PredicateSemanticsNever case ast.KindConditionalExpression: - return c.getSyntacticNullishnessSemantics(node.AsConditionalExpression().WhenTrue) | c.getSyntacticNullishnessSemantics(node.AsConditionalExpression().WhenFalse) + return c.getSyntacticNullishnessSemantics(node.AsConditionalExpression().WhenTrue()) | c.getSyntacticNullishnessSemantics(node.AsConditionalExpression().WhenFalse()) case ast.KindNullKeyword: return PredicateSemanticsAlways case ast.KindIdentifier: @@ -13258,12 +13258,12 @@ func (c *Checker) isSideEffectFree(node *ast.Node) bool { ast.KindJsxElement: return true case ast.KindConditionalExpression: - return c.isSideEffectFree(node.AsConditionalExpression().WhenTrue) && c.isSideEffectFree(node.AsConditionalExpression().WhenFalse) + return c.isSideEffectFree(node.AsConditionalExpression().WhenTrue()) && c.isSideEffectFree(node.AsConditionalExpression().WhenFalse()) case ast.KindBinaryExpression: - if ast.IsAssignmentOperator(node.AsBinaryExpression().OperatorToken.Kind) { + if ast.IsAssignmentOperator(node.AsBinaryExpression().OperatorToken().Kind) { return false } - return c.isSideEffectFree(node.AsBinaryExpression().Left) && c.isSideEffectFree(node.AsBinaryExpression().Right) + return c.isSideEffectFree(node.AsBinaryExpression().Left()) && c.isSideEffectFree(node.AsBinaryExpression().Right()) case ast.KindPrefixUnaryExpression: // Unary operators ~, !, +, and - have no side effects. // The rest do. @@ -13277,11 +13277,11 @@ func (c *Checker) isSideEffectFree(node *ast.Node) bool { // Return true for "indirect calls", (i.e. `(0, x.f)(...)` or `(0, eval)(...)`), which prevents passing `this`. func (c *Checker) isIndirectCall(node *ast.Node) bool { - left := node.AsBinaryExpression().Left - right := node.AsBinaryExpression().Right - return ast.IsParenthesizedExpression(node.Parent) && ast.IsNumericLiteral(left) && left.Text() == "0" && - (ast.IsCallExpression(node.Parent.Parent) && node.Parent.Parent.Expression() == node.Parent || - ast.IsTaggedTemplateExpression(node.Parent.Parent)) && (ast.IsAccessExpression(right) || ast.IsIdentifier(right) && right.Text() == "eval") + left := node.AsBinaryExpression().Left() + right := node.AsBinaryExpression().Right() + return ast.IsParenthesizedExpression(node.Parent()) && ast.IsNumericLiteral(left) && left.Text() == "0" && + (ast.IsCallExpression(node.Parent().Parent()) && node.Parent().Parent().Expression() == node.Parent() || + ast.IsTaggedTemplateExpression(node.Parent().Parent())) && (ast.IsAccessExpression(right) || ast.IsIdentifier(right) && right.Text() == "eval") } func (c *Checker) checkInstanceOfExpression(left *ast.Expression, right *ast.Expression, leftType *Type, rightType *Type, checkMode CheckMode) *Type { @@ -13296,7 +13296,7 @@ func (c *Checker) checkInstanceOfExpression(left *ast.Expression, right *ast.Exp if !IsTypeAny(leftType) && c.allTypesAssignableToKind(leftType, TypeFlagsPrimitive) { c.error(left, diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter) } - signature := c.getResolvedSignature(left.Parent, nil /*candidatesOutArray*/, checkMode) + signature := c.getResolvedSignature(left.Parent(), nil /*candidatesOutArray*/, checkMode) if signature == c.resolvingSignature { // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that // returns a function type. We defer checking and return silentNeverType. @@ -13829,7 +13829,7 @@ func (c *Checker) tryMergeUnionOfObjectTypeAndEmptyObject(t *Type, readonly bool // We approximate own properties as non-methods plus methods that are inside the object literal func (c *Checker) isSpreadableProperty(prop *ast.Symbol) bool { return !core.Some(prop.Declarations, ast.IsPrivateIdentifierClassElementDeclaration) && prop.Flags&(ast.SymbolFlagsMethod|ast.SymbolFlagsGetAccessor|ast.SymbolFlagsSetAccessor) == 0 || - !core.Some(prop.Declarations, func(d *ast.Node) bool { return d.Parent != nil && ast.IsClassLike(d.Parent) }) + !core.Some(prop.Declarations, func(d *ast.Node) bool { return d.Parent() != nil && ast.IsClassLike(d.Parent()) }) } func (c *Checker) getSpreadSymbol(prop *ast.Symbol, readonly bool) *ast.Symbol { @@ -13858,28 +13858,28 @@ func (c *Checker) isEmptyObjectTypeOrSpreadsIntoEmptyObject(t *Type) bool { func (c *Checker) hasDefaultValue(node *ast.Node) bool { return ast.IsBindingElement(node) && node.Initializer() != nil || ast.IsPropertyAssignment(node) && c.hasDefaultValue(node.Initializer()) || - ast.IsShorthandPropertyAssignment(node) && node.AsShorthandPropertyAssignment().ObjectAssignmentInitializer != nil || - ast.IsBinaryExpression(node) && node.AsBinaryExpression().OperatorToken.Kind == ast.KindEqualsToken + ast.IsShorthandPropertyAssignment(node) && node.AsShorthandPropertyAssignment().ObjectAssignmentInitializer() != nil || + ast.IsBinaryExpression(node) && node.AsBinaryExpression().OperatorToken().Kind == ast.KindEqualsToken } func (c *Checker) isConstContext(node *ast.Node) bool { - parent := node.Parent + parent := node.Parent() return ast.IsConstAssertion(parent) || c.isInlineImportAttributes(node) || 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) + (ast.IsPropertyAssignment(parent) || ast.IsShorthandPropertyAssignment(parent) || ast.IsTemplateSpan(parent)) && c.isConstContext(parent.Parent()) } func (c *Checker) isInlineImportAttributes(node *ast.Node) bool { - if !ast.IsObjectLiteralExpression(node) || !ast.IsPropertyAssignment(node.Parent) || node.Parent.Initializer() != node { + if !ast.IsObjectLiteralExpression(node) || !ast.IsPropertyAssignment(node.Parent()) || node.Parent().Initializer() != node { return false } - property := node.Parent + property := node.Parent() if (!ast.IsIdentifier(property.Name()) && !ast.IsStringLiteralLike(property.Name())) || property.Name().Text() != "with" { return false } - options := property.Parent + options := property.Parent() if !ast.IsObjectLiteralExpression(options) { return false } @@ -13896,7 +13896,7 @@ func (c *Checker) isValidConstAssertionArgument(node *ast.Node) bool { return c.isValidConstAssertionArgument(node.Expression()) case ast.KindPrefixUnaryExpression: op := node.AsPrefixUnaryExpression().Operator - arg := node.AsPrefixUnaryExpression().Operand + arg := node.AsPrefixUnaryExpression().Operand() return op == ast.KindMinusToken && (arg.Kind == ast.KindNumericLiteral || arg.Kind == ast.KindBigIntLiteral) || op == ast.KindPlusToken && arg.Kind == ast.KindNumericLiteral case ast.KindPropertyAccessExpression, ast.KindElementAccessExpression: expr := ast.SkipParentheses(node.Expression()) @@ -13956,7 +13956,7 @@ func (c *Checker) checkPropertyAssignment(node *ast.Node, checkMode CheckMode) * func (c *Checker) checkShorthandPropertyAssignment(node *ast.Node, inDestructuringPattern bool, checkMode CheckMode) *Type { var expr *ast.Node if !inDestructuringPattern { - expr = node.AsShorthandPropertyAssignment().ObjectAssignmentInitializer + expr = node.AsShorthandPropertyAssignment().ObjectAssignmentInitializer() } if expr == nil { expr = node.Name() @@ -13980,7 +13980,7 @@ func (c *Checker) isInPropertyInitializerOrClassStaticBlock(node *ast.Node, igno case ast.KindArrowFunction: return core.IfElse(ignoreArrowFunctions, ast.FindAncestorFalse, ast.FindAncestorQuit) case ast.KindBlock: - return core.IfElse(ast.IsFunctionLikeDeclaration(node.Parent) && node.Parent.Kind != ast.KindArrowFunction, ast.FindAncestorQuit, ast.FindAncestorFalse) + return core.IfElse(ast.IsFunctionLikeDeclaration(node.Parent()) && node.Parent().Kind != ast.KindArrowFunction, ast.FindAncestorQuit, ast.FindAncestorFalse) default: return ast.FindAncestorFalse } @@ -14015,7 +14015,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. - case ast.IsBindingElement(declaration) && declaration.Initializer() == nil && !hasDotDotDotToken(declaration) && len(declaration.Parent.Elements()) >= 2: + case ast.IsBindingElement(declaration) && declaration.Initializer() == nil && !hasDotDotDotToken(declaration) && len(declaration.Parent().Elements()) >= 2: rootDeclaration := ast.GetRootDeclaration(declaration) rootInitializer := rootDeclaration.Initializer() // Avoid declaration circularity without blocking binding defaults or nested callbacks. @@ -14024,7 +14024,7 @@ func (c *Checker) getNarrowedTypeOfSymbol(symbol *ast.Symbol, location *ast.Node c.getControlFlowContainer(declaration) == c.getControlFlowContainer(location) { break } - parent := declaration.Parent.Parent + parent := declaration.Parent().Parent() if ast.IsVariableDeclaration(rootDeclaration) && c.getCombinedNodeFlagsCached(rootDeclaration)&ast.NodeFlagsConstant != 0 || ast.IsParameterDeclaration(rootDeclaration) { links := c.nodeLinks.Get(parent) if links.flags&NodeCheckFlagsInCheckIdentifier == 0 { @@ -14037,7 +14037,7 @@ func (c *Checker) getNarrowedTypeOfSymbol(symbol *ast.Symbol, location *ast.Node // Guard parent-type resolution only; flow analysis should allow re-entrant narrowing links.flags &^= NodeCheckFlagsInCheckIdentifier if parentTypeConstraint != nil && parentTypeConstraint.flags&TypeFlagsUnion != 0 && !(ast.IsParameterDeclaration(rootDeclaration) && c.isSomeSymbolAssigned(rootDeclaration)) { - pattern := declaration.Parent + pattern := declaration.Parent() narrowedType := c.getFlowTypeOfReferenceEx(pattern, parentTypeConstraint, parentTypeConstraint, nil /*flowContainer*/, getFlowNodeOfNode(location)) if narrowedType.flags&TypeFlagsNever != 0 { t = c.neverType @@ -14071,7 +14071,7 @@ func (c *Checker) getNarrowedTypeOfSymbol(symbol *ast.Symbol, location *ast.Node // if it occurred in the specified location. We then recompute the narrowed parameter type by indexing into the // narrowed tuple type. case ast.IsParameterDeclaration(declaration) && declaration.Type() == nil && declaration.Initializer() == nil && !hasDotDotDotToken(declaration): - fn := declaration.Parent + fn := declaration.Parent() if len(fn.Parameters()) >= 2 && c.isContextSensitiveFunctionOrObjectLiteralMethod(fn) { contextualSignature := c.getContextualSignature(fn) if contextualSignature != nil && len(contextualSignature.parameters) == 1 && signatureHasRestParameter(contextualSignature) { @@ -14203,12 +14203,12 @@ func (c *Checker) getCannotFindNameDiagnosticForName(node *ast.Node) *diagnostic "AsyncIterableIterator", "AsyncGenerator", "AsyncGeneratorFunction", "BigInt", "Reflect", "BigInt64Array", "BigUint64Array": return diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later case "await": - if ast.IsCallExpression(node.Parent) { + if ast.IsCallExpression(node.Parent()) { return diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function } fallthrough default: - if node.Parent.Kind == ast.KindShorthandPropertyAssignment { + if node.Parent().Kind == ast.KindShorthandPropertyAssignment { return diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer } return diagnostics.Cannot_find_name_0 @@ -14699,7 +14699,7 @@ func (c *Checker) resolveSymbolEx(symbol *ast.Symbol, dontResolveAlias bool) *as func (c *Checker) getTargetOfImportEqualsDeclaration(node *ast.Node) *ast.Symbol { // Node is ImportEqualsDeclaration | VariableDeclaration - if ast.IsVariableDeclaration(node) || node.AsImportEqualsDeclaration().ModuleReference.Kind == ast.KindExternalModuleReference { + if ast.IsVariableDeclaration(node) || node.AsImportEqualsDeclaration().ModuleReference().Kind == ast.KindExternalModuleReference { moduleReference := getExternalModuleRequireArgument(node) if moduleReference == nil { moduleReference = ast.GetExternalModuleImportEqualsDeclarationExpression(node) @@ -14715,7 +14715,7 @@ func (c *Checker) getTargetOfImportEqualsDeclaration(node *ast.Node) *ast.Symbol c.markSymbolOfAliasDeclarationIfTypeOnly(node, nil) return resolved } - resolved := c.getSymbolOfPartOfRightHandSideOfImportEquals(node.AsImportEqualsDeclaration().ModuleReference) + resolved := c.getSymbolOfPartOfRightHandSideOfImportEquals(node.AsImportEqualsDeclaration().ModuleReference()) c.checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) return resolved } @@ -14740,21 +14740,21 @@ func (c *Checker) getSymbolOfPartOfRightHandSideOfImportEquals(entityName *ast.N // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace if entityName.Kind == ast.KindIdentifier && ast.IsRightSideOfQualifiedNameOrPropertyAccess(entityName) { - entityName = entityName.Parent // QualifiedName + entityName = entityName.Parent() // QualifiedName } // Check for case 1 and 3 in the above example - if entityName.Kind == ast.KindIdentifier || entityName.Parent.Kind == ast.KindQualifiedName { + if entityName.Kind == ast.KindIdentifier || entityName.Parent().Kind == ast.KindQualifiedName { return c.resolveEntityName(entityName, ast.SymbolFlagsNamespace, false /*ignoreErrors*/, true /*dontResolveAlias*/, nil /*location*/) } // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - debug.Assert(entityName.Parent.Kind == ast.KindImportEqualsDeclaration) + debug.Assert(entityName.Parent().Kind == ast.KindImportEqualsDeclaration) return c.resolveEntityName(entityName, ast.SymbolFlagsValue|ast.SymbolFlagsType|ast.SymbolFlagsNamespace, false /*ignoreErrors*/, true /*dontResolveAlias*/, nil /*location*/) } func (c *Checker) checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node *ast.Node, resolved *ast.Symbol) { decl := node.AsImportEqualsDeclaration() - name := decl.ModuleReference + name := decl.ModuleReference() for { if typeOnlyDeclaration := c.getTypeOnlyDeclarationOfEntityName(name); typeOnlyDeclaration != nil { isExport := ast.NodeKindIs(typeOnlyDeclaration, ast.KindExportSpecifier, ast.KindExportDeclaration) @@ -14769,13 +14769,13 @@ func (c *Checker) checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(nod if !ast.IsExportDeclaration(typeOnlyDeclaration) { name = typeOnlyDeclaration.Name().Text() } - c.error(decl.ModuleReference, message).AddRelatedInfo(createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name)) + c.error(decl.ModuleReference(), message).AddRelatedInfo(createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name)) break } if ast.IsIdentifier(name) { break } - name = name.AsQualifiedName().Left + name = name.AsQualifiedName().Left() } } @@ -14798,7 +14798,7 @@ func (c *Checker) getTargetOfImportClause(node *ast.Node) *ast.Symbol { } return links.immediateTarget } - moduleSymbol := c.resolveExternalModuleName(node, getModuleSpecifierFromNode(node.Parent), false /*ignoreErrors*/, c.getTypeFromImportAttributes(ast.GetImportAttributes(node.Parent))) + moduleSymbol := c.resolveExternalModuleName(node, getModuleSpecifierFromNode(node.Parent()), false /*ignoreErrors*/, c.getTypeFromImportAttributes(ast.GetImportAttributes(node.Parent()))) if moduleSymbol != nil { return c.getTargetOfModuleDefault(moduleSymbol, node, true /*dontResolveAlias*/) } @@ -14836,11 +14836,11 @@ func (c *Checker) getTargetOfModuleDefault(moduleSymbol *ast.Symbol, node *ast.N // node is ImportClause | ImportSpecifier | ExportSpecifier var attributes *ast.ImportAttributesNode if ast.IsImportClause(node) { - attributes = ast.GetImportAttributes(node.Parent) + attributes = ast.GetImportAttributes(node.Parent()) } else if ast.IsImportSpecifier(node) { - attributes = ast.GetImportAttributes(node.Parent.Parent.Parent) + attributes = ast.GetImportAttributes(node.Parent().Parent().Parent()) } else if ast.IsExportSpecifier(node) { - attributes = ast.GetImportAttributes(node.Parent.Parent) + attributes = ast.GetImportAttributes(node.Parent().Parent()) } hasDefaultOnly := c.isOnlyImportableAsDefault(specifier, moduleSymbol, c.getTypeFromImportAttributes(attributes)) hasSyntheticDefault := c.canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, specifier) @@ -14908,7 +14908,7 @@ func (c *Checker) resolveExportByName(moduleSymbol *ast.Symbol, name string, sou func (c *Checker) getTargetOfNamespaceImport(node *ast.Node) *ast.Symbol { moduleSpecifier := c.getModuleSpecifierForImportOrExport(node) - immediate := c.resolveExternalModuleName(node, moduleSpecifier, false /*ignoreErrors*/, c.getTypeFromImportAttributes(ast.GetImportAttributes(node.Parent.Parent))) + immediate := c.resolveExternalModuleName(node, moduleSpecifier, false /*ignoreErrors*/, c.getTypeFromImportAttributes(ast.GetImportAttributes(node.Parent().Parent()))) resolved := c.resolveESModuleSymbol(immediate, node, moduleSpecifier) c.markSymbolOfAliasDeclarationIfTypeOnly(node, nil) return resolved @@ -14917,7 +14917,7 @@ func (c *Checker) getTargetOfNamespaceImport(node *ast.Node) *ast.Symbol { func (c *Checker) getTargetOfNamespaceExport(node *ast.Node) *ast.Symbol { moduleSpecifier := c.getModuleSpecifierForImportOrExport(node) if moduleSpecifier != nil { - immediate := c.resolveExternalModuleName(node, moduleSpecifier, false /*ignoreErrors*/, c.getTypeFromImportAttributes(ast.GetImportAttributes(node.Parent))) + immediate := c.resolveExternalModuleName(node, moduleSpecifier, false /*ignoreErrors*/, c.getTypeFromImportAttributes(ast.GetImportAttributes(node.Parent()))) resolved := c.resolveESModuleSymbol(immediate, node, moduleSpecifier) c.markSymbolOfAliasDeclarationIfTypeOnly(node, nil) return resolved @@ -14930,13 +14930,13 @@ func (c *Checker) getTargetOfImportSpecifier(node *ast.Node) *ast.Symbol { if ast.IsImportSpecifier(node) && ast.ModuleExportNameIsDefault(name) { specifier := c.getModuleSpecifierForImportOrExport(node) if specifier != nil { - moduleSymbol := c.resolveExternalModuleName(node, specifier, false /*ignoreErrors*/, c.getTypeFromImportAttributes(ast.GetImportAttributes(node.Parent.Parent.Parent))) + moduleSymbol := c.resolveExternalModuleName(node, specifier, false /*ignoreErrors*/, c.getTypeFromImportAttributes(ast.GetImportAttributes(node.Parent().Parent().Parent()))) if moduleSymbol != nil { return c.getTargetOfModuleDefault(moduleSymbol, node, true /*dontResolveAlias*/) } } } - root := node.Parent.Parent.Parent // ImportDeclaration + root := node.Parent().Parent().Parent() // ImportDeclaration if ast.IsBindingElement(node) { root = ast.GetRootDeclaration(node) } @@ -15239,13 +15239,13 @@ func (c *Checker) getTargetOfExportSpecifier(node *ast.Node, meaning ast.SymbolF if ast.ModuleExportNameIsDefault(name) { specifier := c.getModuleSpecifierForImportOrExport(node) if specifier != nil { - moduleSymbol := c.resolveExternalModuleName(node, specifier, false /*ignoreErrors*/, c.getTypeFromImportAttributes(ast.GetImportAttributes(node.Parent.Parent))) + moduleSymbol := c.resolveExternalModuleName(node, specifier, false /*ignoreErrors*/, c.getTypeFromImportAttributes(ast.GetImportAttributes(node.Parent().Parent()))) if moduleSymbol != nil { return c.getTargetOfModuleDefault(moduleSymbol, node, dontResolveAlias) } } } - exportDeclaration := node.Parent.Parent + exportDeclaration := node.Parent().Parent() var resolved *ast.Symbol switch { case exportDeclaration.ModuleSpecifier() != nil: @@ -15274,7 +15274,7 @@ func (c *Checker) getTargetOfExportAssignment(node *ast.Node) *ast.Symbol { } func (c *Checker) getTargetOfBinaryExpression(node *ast.Node) *ast.Symbol { - resolved := c.getTargetOfAliasLikeExpression(node.AsBinaryExpression().Right) + resolved := c.getTargetOfAliasLikeExpression(node.AsBinaryExpression().Right()) c.markSymbolOfAliasDeclarationIfTypeOnly(node, nil) return resolved } @@ -15295,8 +15295,8 @@ func (c *Checker) getTargetOfAliasLikeExpression(expression *ast.Node) *ast.Symb } func (c *Checker) getTargetOfNamespaceExportDeclaration(node *ast.Node) *ast.Symbol { - if ast.CanHaveSymbol(node.Parent) { - resolved := c.resolveExternalModuleSymbol(node.Parent.Symbol(), true /*dontResolveAlias*/) + if ast.CanHaveSymbol(node.Parent()) { + resolved := c.resolveExternalModuleSymbol(node.Parent().Symbol(), true /*dontResolveAlias*/) c.markSymbolOfAliasDeclarationIfTypeOnly(node, nil) return resolved } @@ -15304,10 +15304,10 @@ func (c *Checker) getTargetOfNamespaceExportDeclaration(node *ast.Node) *ast.Sym } func (c *Checker) getTargetOfAccessExpression(node *ast.Node) *ast.Symbol { - if ast.IsBinaryExpression(node.Parent) { - expr := node.Parent.AsBinaryExpression() - if expr.Left == node && expr.OperatorToken.Kind == ast.KindEqualsToken { - return c.getTargetOfAliasLikeExpression(expr.Right) + if ast.IsBinaryExpression(node.Parent()) { + expr := node.Parent().AsBinaryExpression() + if expr.Left() == node && expr.OperatorToken().Kind == ast.KindEqualsToken { + return c.getTargetOfAliasLikeExpression(expr.Right()) } } return nil @@ -15316,21 +15316,21 @@ func (c *Checker) getTargetOfAccessExpression(node *ast.Node) *ast.Symbol { func (c *Checker) getModuleSpecifierForImportOrExport(node *ast.Node) *ast.Node { switch node.Kind { case ast.KindImportClause: - return getModuleSpecifierFromNode(node.Parent) + return getModuleSpecifierFromNode(node.Parent()) case ast.KindImportEqualsDeclaration: - if ast.IsExternalModuleReference(node.AsImportEqualsDeclaration().ModuleReference) { - return node.AsImportEqualsDeclaration().ModuleReference.Expression() + if ast.IsExternalModuleReference(node.AsImportEqualsDeclaration().ModuleReference()) { + return node.AsImportEqualsDeclaration().ModuleReference().Expression() } else { return nil } case ast.KindNamespaceImport: - return getModuleSpecifierFromNode(node.Parent.Parent) + return getModuleSpecifierFromNode(node.Parent().Parent()) case ast.KindImportSpecifier: - return getModuleSpecifierFromNode(node.Parent.Parent.Parent) + return getModuleSpecifierFromNode(node.Parent().Parent().Parent()) case ast.KindNamespaceExport: - return getModuleSpecifierFromNode(node.Parent) + return getModuleSpecifierFromNode(node.Parent()) case ast.KindExportSpecifier: - return getModuleSpecifierFromNode(node.Parent.Parent) + return getModuleSpecifierFromNode(node.Parent().Parent()) } panic("Unhandled case in getModuleSpecifierForImportOrExport") } @@ -15407,7 +15407,7 @@ func (c *Checker) getCannotResolveModuleNameErrorForSpecificModule(moduleName *a func (c *Checker) resolveExternalModuleNameWorker(location *ast.Node, moduleReferenceExpression *ast.Node, moduleNotFoundError *diagnostics.Message, ignoreErrors bool, isForAugmentation bool, importAttributesType *Type) *ast.Symbol { if ast.IsStringLiteralLike(moduleReferenceExpression) { - if ast.IsSourcePhaseImport(moduleReferenceExpression.Parent) { + if ast.IsSourcePhaseImport(moduleReferenceExpression.Parent()) { return nil } return c.resolveExternalModule(location, moduleReferenceExpression.Text(), moduleNotFoundError, core.IfElse(!ignoreErrors, moduleReferenceExpression, nil), isForAugmentation, importAttributesType) @@ -15469,12 +15469,12 @@ func (c *Checker) resolveExternalModule( mode core.ResolutionMode ) - if ast.IsStringLiteralLike(location) || location.Parent != nil && ast.IsModuleDeclaration(location.Parent) && location.Parent.AsModuleDeclaration().Name() == location { + if ast.IsStringLiteralLike(location) || location.Parent() != nil && ast.IsModuleDeclaration(location.Parent()) && location.Parent().AsModuleDeclaration().Name() == location { contextSpecifier = location } else if ast.IsModuleDeclaration(location) { contextSpecifier = location.AsModuleDeclaration().Name() } else if ast.IsLiteralImportTypeNode(location) { - contextSpecifier = location.AsImportTypeNode().Argument.AsLiteralTypeNode().Literal + contextSpecifier = location.AsImportTypeNode().Argument().AsLiteralTypeNode().Literal() } else if ast.IsVariableDeclarationInitializedToBareOrAccessedRequire(location) { contextSpecifier = ast.GetModuleSpecifierOfBareOrAccessedRequire(location) } else { @@ -15498,7 +15498,7 @@ func (c *Checker) resolveExternalModule( if ancestor == nil { ancestor = ast.FindAncestor(location, ast.IsImportEqualsDeclaration) if ancestor != nil { - if moduleRefrence := ancestor.AsImportEqualsDeclaration().ModuleReference; moduleRefrence.Kind == ast.KindExternalModuleReference { + if moduleRefrence := ancestor.AsImportEqualsDeclaration().ModuleReference(); moduleRefrence.Kind == ast.KindExternalModuleReference { contextSpecifier = moduleRefrence.Expression() } } @@ -15950,7 +15950,7 @@ func (c *Checker) resolveESModuleSymbol(moduleSymbol *ast.Symbol, node *ast.Node symbol = c.getMergedSymbol(c.resolveIndirectionAlias(c.getSymbolOfDeclaration(node), symbol)) } if symbol != nil { - referenceParent := moduleSpecifier.Parent + referenceParent := moduleSpecifier.Parent() var namespaceImport *ast.Node if ast.IsImportDeclaration(referenceParent) { namespaceImport = ast.GetNamespaceDeclarationNode(referenceParent) @@ -16183,16 +16183,16 @@ func (c *Checker) resolveEntityName(name *ast.Node, meaning ast.SymbolFlags, ign } case ast.KindQualifiedName: qualified := name.AsQualifiedName() - symbol = c.resolveQualifiedName(name, qualified.Left, qualified.Right, meaning, ignoreErrors, location) + symbol = c.resolveQualifiedName(name, qualified.Left(), qualified.Right(), meaning, ignoreErrors, location) case ast.KindPropertyAccessExpression: access := name.AsPropertyAccessExpression() - symbol = c.resolveQualifiedName(name, access.Expression, access.Name(), meaning, ignoreErrors, location) + symbol = c.resolveQualifiedName(name, access.Expression(), access.Name(), meaning, ignoreErrors, location) default: panic("Unknown entity name kind") } if symbol != nil && symbol != c.unknownSymbol { if !ast.NodeIsSynthesized(name) && ast.IsEntityName(name) && - (symbol.Flags&ast.SymbolFlagsAlias != 0 || name.Parent != nil && name.Parent.Kind == ast.KindExportAssignment) { + (symbol.Flags&ast.SymbolFlagsAlias != 0 || name.Parent() != nil && name.Parent().Kind == ast.KindExportAssignment) { c.markSymbolOfAliasDeclarationIfTypeOnly(getAliasDeclarationFromName(name), nil) } // We know a symbol with the given meaning exists along the alias chain, so resolve until we find it. @@ -16245,17 +16245,17 @@ func (c *Checker) resolveQualifiedName(name *ast.Node, left *ast.Node, right *as if ast.IsQualifiedName(name) { containingQualifiedName = getContainingQualifiedNameNode(name) } - canSuggestTypeof := c.globalObjectType != nil && meaning&ast.SymbolFlagsType != 0 && containingQualifiedName != nil && !ast.IsTypeOfExpression(containingQualifiedName.Parent) && c.tryGetQualifiedNameAsValue(containingQualifiedName) != nil + canSuggestTypeof := c.globalObjectType != nil && meaning&ast.SymbolFlagsType != 0 && containingQualifiedName != nil && !ast.IsTypeOfExpression(containingQualifiedName.Parent()) && c.tryGetQualifiedNameAsValue(containingQualifiedName) != nil if canSuggestTypeof { c.error(containingQualifiedName, diagnostics.X_0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, entityNameToString(containingQualifiedName)) return nil } if meaning&ast.SymbolFlagsNamespace != 0 { - if ast.IsQualifiedName(name.Parent) { + if ast.IsQualifiedName(name.Parent()) { 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.Text()) + 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().Text()) return nil } } @@ -16273,13 +16273,13 @@ func (c *Checker) tryGetQualifiedNameAsValue(node *ast.Node) *ast.Symbol { return nil } n := id - for ast.IsQualifiedName(n.Parent) { + for ast.IsQualifiedName(n.Parent()) { t := c.getTypeOfSymbol(symbol) - symbol = c.getPropertyOfType(t, n.Parent.AsQualifiedName().Right.Text()) + symbol = c.getPropertyOfType(t, n.Parent().AsQualifiedName().Right().Text()) if symbol == nil { return nil } - n = n.Parent + n = n.Parent() } return symbol } @@ -16389,13 +16389,13 @@ func (c *Checker) lateBindMember(parent *ast.Symbol, earlySymbols ast.SymbolTabl links.resolvedSymbol = decl.Symbol() var declName *ast.Node if ast.IsBinaryExpression(decl) { - declName = decl.AsBinaryExpression().Left + declName = decl.AsBinaryExpression().Left() } else { declName = decl.Name() } var t *Type if ast.IsElementAccessExpression(declName) { - t = c.checkExpressionCached(declName.AsElementAccessExpression().ArgumentExpression) + t = c.checkExpressionCached(declName.AsElementAccessExpression().ArgumentExpression()) } else { t = c.checkComputedPropertyName(declName) } @@ -16837,9 +16837,9 @@ func (c *Checker) GetTypeOfSymbolAtLocation(symbol *ast.Symbol, location *ast.No // of the expression (which will reflect control flow analysis). If the expression indeed // resolved to the given symbol, return the narrowed type. if (ast.IsIdentifier(location) || ast.IsPrivateIdentifier(location)) && - !(ast.IsJsxTagName(location) || ast.IsJsxAttribute(location.Parent) || ast.IsJsxNamespacedName(location.Parent)) { + !(ast.IsJsxTagName(location) || ast.IsJsxAttribute(location.Parent()) || ast.IsJsxNamespacedName(location.Parent())) { if ast.IsRightSideOfQualifiedNameOrPropertyAccess(location) { - location = location.Parent + location = location.Parent() } if ast.IsExpressionNode(location) && (!ast.IsAssignmentTarget(location) || ast.IsWriteAccess(location)) { var t *Type @@ -16853,15 +16853,15 @@ func (c *Checker) GetTypeOfSymbolAtLocation(symbol *ast.Symbol, location *ast.No } } } - if ast.IsDeclarationName(location) && ast.IsSetAccessorDeclaration(location.Parent) && c.getAnnotatedAccessorTypeNode(location.Parent) != nil { - return c.getWriteTypeOfAccessors(location.Parent.Symbol()) + if ast.IsDeclarationName(location) && ast.IsSetAccessorDeclaration(location.Parent()) && c.getAnnotatedAccessorTypeNode(location.Parent()) != nil { + return c.getWriteTypeOfAccessors(location.Parent().Symbol()) } // The location isn't a reference to the given symbol, meaning we're being asked // a hypothetical question of what type the symbol would have if there was a reference // to it at the given location. Since we have no control flow information for the // hypothetical reference (control flow information is created and attached by the // binder), we simply return the declared type of the symbol. - if isRightSideOfAccessExpression(location) && ast.IsWriteAccess(location.Parent) { + if isRightSideOfAccessExpression(location) && ast.IsWriteAccess(location.Parent()) { return c.getWriteTypeOfSymbol(symbol) } } @@ -16948,7 +16948,7 @@ func (c *Checker) isParameterOfContextSensitiveSignature(symbol *ast.Symbol) boo decl = ast.WalkUpBindingElementsAndPatterns(decl) } if ast.IsParameterDeclaration(decl) { - return c.isContextSensitiveFunctionOrObjectLiteralMethod(decl.Parent) + return c.isContextSensitiveFunctionOrObjectLiteralMethod(decl.Parent()) } return false } @@ -17031,7 +17031,7 @@ func (c *Checker) getTypeForVariableLikeDeclaration(declaration *ast.Node, inclu // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. if ast.IsVariableDeclaration(declaration) { - grandParent := declaration.Parent.Parent + grandParent := declaration.Parent().Parent() switch grandParent.Kind { case ast.KindForInStatement: indexType := c.getIndexType(c.getNonNullableTypeIfNeeded(c.checkExpressionEx(grandParent.Expression(), checkMode /*checkMode*/))) @@ -17092,10 +17092,10 @@ func (c *Checker) getTypeForVariableLikeDeclaration(declaration *ast.Node, inclu // parameters of function types defined in JSDoc in TS files don't have symbols return nil } - fn := declaration.Parent + fn := declaration.Parent() // For a parameter of a set accessor, use the type of the get accessor if one is present if ast.IsSetAccessorDeclaration(fn) && c.hasBindableName(fn) { - getter := ast.GetDeclarationOfKind(c.getSymbolOfDeclaration(declaration.Parent), ast.KindGetAccessor) + getter := ast.GetDeclarationOfKind(c.getSymbolOfDeclaration(declaration.Parent()), ast.KindGetAccessor) if getter != nil { getterSignature := c.getSignatureFromDeclaration(getter) thisParameter := c.getAccessorThisParameter(fn) @@ -17131,7 +17131,7 @@ func (c *Checker) getTypeForVariableLikeDeclaration(declaration *ast.Node, inclu // We have a property declaration with no type annotation or initializer, in noImplicitAny mode or a .js file. // Use control flow analysis of this.xxx assignments in the constructor or static block to determine the type of the property. if !ast.HasStaticModifier(declaration) { - constructor := ast.FindConstructorDeclaration(declaration.Parent) + constructor := ast.FindConstructorDeclaration(declaration.Parent()) var t *Type switch { case constructor != nil: @@ -17144,7 +17144,7 @@ func (c *Checker) getTypeForVariableLikeDeclaration(declaration *ast.Node, inclu } return c.addOptionalityEx(t, true /*isProperty*/, isOptional) } else { - staticBlocks := core.Filter(declaration.Parent.Members(), ast.IsClassStaticBlockDeclaration) + staticBlocks := core.Filter(declaration.Parent().Members(), ast.IsClassStaticBlockDeclaration) var t *Type switch { case len(staticBlocks) != 0: @@ -17464,7 +17464,7 @@ func (c *Checker) getConstraintFromTypeParameter(t *Type) *Type { if constraint.flags&TypeFlagsAny != 0 && !c.isErrorType(constraint) { // use stringNumberSymbolType as the base constraint for mapped type key constraints (unknown isn;t assignable to that, but `any` was), // use unknown otherwise - if ast.IsMappedTypeNode(constraintDeclaration.Parent.Parent) { + if ast.IsMappedTypeNode(constraintDeclaration.Parent().Parent()) { constraint = c.stringNumberSymbolType } else { constraint = c.unknownType @@ -17494,16 +17494,16 @@ func (c *Checker) getInferredTypeParameterConstraint(t *Type, omitTypeReferences var inferences []*Type if t.symbol != nil && len(t.symbol.Declarations) != 0 { for _, declaration := range t.symbol.Declarations { - if ast.IsInferTypeNode(declaration.Parent) { + if ast.IsInferTypeNode(declaration.Parent()) { // When an 'infer T' declaration is immediately contained in a type reference node // (such as 'Foo'), T's constraint is inferred from the constraint of the // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are // present, we form an intersection of the inferred constraint types. - child := declaration.Parent - parent := child.Parent + child := declaration.Parent() + parent := child.Parent() for parent != nil && ast.IsParenthesizedTypeNode(parent) { child = parent - parent = child.Parent + parent = child.Parent() } switch { case ast.IsTypeReferenceNode(parent) && !omitTypeReferences: @@ -17531,26 +17531,26 @@ func (c *Checker) getInferredTypeParameterConstraint(t *Type, omitTypeReferences } } } - case ast.IsParameterDeclaration(parent) && parent.AsParameterDeclaration().DotDotDotToken != nil || + case ast.IsParameterDeclaration(parent) && parent.AsParameterDeclaration().DotDotDotToken() != nil || ast.IsRestTypeNode(parent) || - ast.IsNamedTupleMember(parent) && parent.AsNamedTupleMember().DotDotDotToken != nil: + ast.IsNamedTupleMember(parent) && parent.AsNamedTupleMember().DotDotDotToken() != nil: inferences = append(inferences, c.createArrayType(c.unknownType)) case ast.IsTemplateLiteralTypeSpan(parent): inferences = append(inferences, c.stringType) - case ast.IsTypeParameterDeclaration(parent) && ast.IsMappedTypeNode(parent.Parent): + case ast.IsTypeParameterDeclaration(parent) && ast.IsMappedTypeNode(parent.Parent()): inferences = append(inferences, c.stringNumberSymbolType) 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.Type() != nil: - checkMappedType := parent.Parent.AsConditionalTypeNode().CheckType + 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().Type() != nil: + checkMappedType := parent.Parent().AsConditionalTypeNode().CheckType() nodeType := c.getTypeFromTypeNode(checkMappedType.Type()) - checkMappedTypeParameter := checkMappedType.AsMappedTypeNode().TypeParameter + checkMappedTypeParameter := checkMappedType.AsMappedTypeNode().TypeParameter() mapper := newSimpleTypeMapper(c.getDeclaredTypeOfTypeParameter(c.getSymbolOfDeclaration(checkMappedTypeParameter)), - core.IfElse(checkMappedTypeParameter.AsTypeParameterDeclaration().Constraint != nil, - c.getTypeFromTypeNode(checkMappedTypeParameter.AsTypeParameterDeclaration().Constraint), + core.IfElse(checkMappedTypeParameter.AsTypeParameterDeclaration().Constraint() != nil, + c.getTypeFromTypeNode(checkMappedTypeParameter.AsTypeParameterDeclaration().Constraint()), c.stringNumberSymbolType)) inferences = append(inferences, c.instantiateType(nodeType, mapper)) } @@ -18052,7 +18052,7 @@ func isUnconstrainedTypeParameter(tp *Type) bool { return false } for _, d := range target.symbol.Declarations { - if ast.IsTypeParameterDeclaration(d) && (d.AsTypeParameterDeclaration().Constraint != nil || ast.IsMappedTypeNode(d.Parent) || ast.IsInferTypeNode(d.Parent)) { + if ast.IsTypeParameterDeclaration(d) && (d.AsTypeParameterDeclaration().Constraint() != nil || ast.IsMappedTypeNode(d.Parent()) || ast.IsInferTypeNode(d.Parent())) { return false } } @@ -18071,14 +18071,14 @@ func (c *Checker) isNullOrUndefined(node *ast.Node) bool { } func (c *Checker) checkRightHandSideOfForOf(statement *ast.Node) *Type { - use := core.IfElse(statement.AsForInOrOfStatement().AwaitModifier != nil, IterationUseForAwaitOf, IterationUseForOf) + use := core.IfElse(statement.AsForInOrOfStatement().AwaitModifier() != nil, IterationUseForAwaitOf, IterationUseForOf) return c.checkIteratedTypeOrElementType(use, c.checkNonNullExpression(statement.Expression()), c.undefinedType, statement.Expression()) } // Return the inferred type for a binding element func (c *Checker) getTypeForBindingElement(declaration *ast.Node) *Type { checkMode := core.IfElse(hasDotDotDotToken(declaration), CheckModeRestBindingElement, CheckModeNormal) - parentType := c.getTypeForBindingElementParent(declaration.Parent.Parent, checkMode) + parentType := c.getTypeForBindingElementParent(declaration.Parent().Parent(), checkMode) if parentType != nil { return c.getBindingElementTypeFromParentType(declaration, parentType, false /*noTupleBoundsCheck*/) } @@ -18104,11 +18104,11 @@ func (c *Checker) getBindingElementTypeFromParentType(declaration *ast.Node, par if IsTypeAny(parentType) { return parentType } - pattern := declaration.Parent + pattern := declaration.Parent() // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation if c.strictNullChecks && declaration.Flags&ast.NodeFlagsAmbient != 0 && ast.IsPartOfParameterDeclaration(declaration) { parentType = c.GetNonNullableType(parentType) - } else if c.strictNullChecks && pattern.Parent.Initializer() != nil && !c.hasTypeFacts(c.getTypeOfInitializer(pattern.Parent.Initializer()), TypeFactsEQUndefined) { + } else if c.strictNullChecks && pattern.Parent().Initializer() != nil && !c.hasTypeFacts(c.getTypeOfInitializer(pattern.Parent().Initializer()), TypeFactsEQUndefined) { parentType = c.getTypeWithFacts(parentType, TypeFactsNEUndefined) } accessFlags := AccessFlagsExpressionPosition | core.IfElse(noTupleBoundsCheck || c.hasDefaultValue(declaration), AccessFlagsAllowMissing, 0) @@ -18262,12 +18262,12 @@ func (c *Checker) getSyntheticElementAccess(node *ast.Node) *ast.Node { } result := c.factory.NewElementAccessExpression(lhsExpr, nil, literal, ast.NodeFlagsNone) result.Loc = node.Loc - literal.Parent = result - result.Parent = node + literal.SetParent(result) + result.SetParent(node) if lhsExpr != parentAccess { - lhsExpr.Parent = result + lhsExpr.SetParent(result) } - result.FlowNodeData().FlowNode = getFlowNodeOfNode(parentAccess) + ast.SetFlowNode(result, getFlowNodeOfNode(parentAccess)) return result } } @@ -18275,16 +18275,16 @@ func (c *Checker) getSyntheticElementAccess(node *ast.Node) *ast.Node { } func (c *Checker) getParentElementAccess(node *ast.Node) *ast.Node { - ancestor := node.Parent.Parent + ancestor := node.Parent().Parent() switch ancestor.Kind { case ast.KindBindingElement, ast.KindPropertyAssignment: return c.getSyntheticElementAccess(ancestor) case ast.KindArrayLiteralExpression: - return c.getSyntheticElementAccess(node.Parent) + return c.getSyntheticElementAccess(node.Parent()) case ast.KindVariableDeclaration: return ancestor.Initializer() case ast.KindBinaryExpression: - return ancestor.AsBinaryExpression().Right + return ancestor.AsBinaryExpression().Right() } return nil } @@ -18428,7 +18428,7 @@ func (c *Checker) getTypeFromBindingElement(element *ast.Node, includePatternInT func (c *Checker) declarationBelongsToPrivateAmbientMember(declaration *ast.Node) bool { memberDeclaration := ast.GetRootDeclaration(declaration) if ast.IsParameterDeclaration(memberDeclaration) { - memberDeclaration = memberDeclaration.Parent + memberDeclaration = memberDeclaration.Parent() } return isPrivateWithinAmbient(memberDeclaration) } @@ -18515,12 +18515,12 @@ func (c *Checker) getAssignmentDeclarationInitializerType(node *ast.Node) *Type case ast.JSDeclarationKindModuleExports, ast.JSDeclarationKindExportsProperty: t = c.getRegularTypeOfLiteralType(c.checkExpressionCached(ast.GetRightMostAssignedExpression(node))) case ast.JSDeclarationKindThisProperty: - if c.containsSameNamedThisProperty(node.AsBinaryExpression().Left, node.AsBinaryExpression().Right) { + if c.containsSameNamedThisProperty(node.AsBinaryExpression().Left(), node.AsBinaryExpression().Right()) { return nil } fallthrough default: - t = c.checkExpressionForMutableLocation(node.AsBinaryExpression().Right, CheckModeNormal) + t = c.checkExpressionForMutableLocation(node.AsBinaryExpression().Right(), CheckModeNormal) } if c.isEmptyArrayLiteralType(t) && !c.hasParentWithTypeAnnotation(node.Symbol()) { c.reportImplicitAny(node, c.anyArrayType, WideningKindNormal) @@ -18541,7 +18541,7 @@ func (c *Checker) getAssignmentDeclarationInitializerType(node *ast.Node) *Type // f.a = []; func (c *Checker) hasParentWithTypeAnnotation(symbol *ast.Symbol) bool { if symbol.Parent != nil && symbol.Parent.ValueDeclaration != nil && ast.IsFunctionExpressionOrArrowFunction(symbol.Parent.ValueDeclaration) { - if possiblyAnnotatedSymbol := c.getSymbolOfNode(symbol.Parent.ValueDeclaration.Parent); possiblyAnnotatedSymbol != nil && possiblyAnnotatedSymbol.ValueDeclaration != nil { + if possiblyAnnotatedSymbol := c.getSymbolOfNode(symbol.Parent.ValueDeclaration.Parent()); possiblyAnnotatedSymbol != nil && possiblyAnnotatedSymbol.ValueDeclaration != nil { return possiblyAnnotatedSymbol.ValueDeclaration.Type() != nil } } @@ -18603,9 +18603,9 @@ func (c *Checker) isConstructorDeclaredThisProperty(symbol *ast.Symbol) (thisAss } bin := declaration.AsBinaryExpression() if ast.GetAssignmentDeclarationKind(declaration) == ast.JSDeclarationKindThisProperty && - (bin.Left.Kind != ast.KindElementAccessExpression || ast.IsStringOrNumericLiteralLike(bin.Left.AsElementAccessExpression().ArgumentExpression)) { - if bin.Type != nil { - typeAnnotation = bin.Type + (bin.Left().Kind != ast.KindElementAccessExpression || ast.IsStringOrNumericLiteralLike(bin.Left().AsElementAccessExpression().ArgumentExpression())) { + if bin.Type() != nil { + typeAnnotation = bin.Type() } } else { allThis = false @@ -18638,7 +18638,7 @@ func (c *Checker) widenTypeForVariableLikeDeclaration(t *Type, declaration *ast. if t != nil { // This special case is required for backwards compatibility with libraries that merge a `symbol` property into `SymbolConstructor`. // See https://github.com/microsoft/TypeScript/tsc/issues/1212 - if t.flags&TypeFlagsESSymbol != 0 && c.isGlobalSymbolConstructor(declaration.Parent) { + if t.flags&TypeFlagsESSymbol != 0 && c.isGlobalSymbolConstructor(declaration.Parent()) { t = c.getESSymbolLikeTypeForNode(declaration) } @@ -18653,7 +18653,7 @@ func (c *Checker) widenTypeForVariableLikeDeclaration(t *Type, declaration *ast. return c.getWidenedType(t) } // Rest parameters default to type any[], other parameters default to type any - if ast.IsParameterDeclaration(declaration) && declaration.AsParameterDeclaration().DotDotDotToken != nil { + if ast.IsParameterDeclaration(declaration) && declaration.AsParameterDeclaration().DotDotDotToken() != nil { t = c.anyArrayType } else { t = c.anyType @@ -18684,17 +18684,17 @@ func (c *Checker) reportImplicitAny(declaration *ast.Node, t *Type, wideningKind if ast.IsIdentifier(param.Name()) { name := param.Name().AsIdentifier() originalKeywordKind := scanner.IdentifierToKeywordKind(name) - if (ast.IsCallSignatureDeclaration(declaration.Parent) || ast.IsMethodSignatureDeclaration(declaration.Parent) || ast.IsFunctionTypeNode(declaration.Parent)) && - slices.Contains(declaration.Parent.Parameters(), declaration) && + if (ast.IsCallSignatureDeclaration(declaration.Parent()) || ast.IsMethodSignatureDeclaration(declaration.Parent()) || ast.IsFunctionTypeNode(declaration.Parent())) && + slices.Contains(declaration.Parent().Parameters(), declaration) && (ast.IsTypeNodeKind(originalKeywordKind) || c.resolveName(declaration, name.Text, ast.SymbolFlagsType, nil /*nameNotFoundMessage*/, true /*isUse*/, false /*excludeGlobals*/) != nil) { - newName := fmt.Sprintf("arg%v", slices.Index(declaration.Parent.Parameters(), declaration)) - typeName := scanner.DeclarationNameToString(param.Name()) + core.IfElse(param.DotDotDotToken != nil, "[]", "") + newName := fmt.Sprintf("arg%v", slices.Index(declaration.Parent().Parameters(), declaration)) + typeName := scanner.DeclarationNameToString(param.Name()) + core.IfElse(param.DotDotDotToken() != nil, "[]", "") c.errorOrSuggestion(c.noImplicitAny, declaration, diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, typeName) return } } switch { - case param.DotDotDotToken != nil: + case param.DotDotDotToken() != nil: if c.noImplicitAny { diagnostic = diagnostics.Rest_parameter_0_implicitly_has_an_any_type } else { @@ -20058,13 +20058,13 @@ func (c *Checker) getIndexInfosOfIndexSymbol(indexSymbol *ast.Symbol, siblingSym } else if c.hasLateBindableIndexSignature(declaration) { var declName *ast.Node if ast.IsBinaryExpression(declaration) { - declName = declaration.AsBinaryExpression().Left + declName = declaration.AsBinaryExpression().Left() } else { declName = declaration.Name() } var keyType *Type if ast.IsElementAccessExpression(declName) { - keyType = c.checkExpressionCached(declName.AsElementAccessExpression().ArgumentExpression) + keyType = c.checkExpressionCached(declName.AsElementAccessExpression().ArgumentExpression()) } else { keyType = c.checkComputedPropertyName(declName) } @@ -20213,7 +20213,7 @@ func (c *Checker) getSignaturesOfSymbol(symbol *ast.Symbol) []*Signature { // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). if i > 0 && decl.Body() != nil { previous := symbol.Declarations[i-1] - if decl.Parent == previous.Parent && decl.Kind == previous.Kind && + if decl.Parent() == previous.Parent() && decl.Kind == previous.Kind && (decl.Pos() == previous.End() || previous.Flags&ast.NodeFlagsReparsed != 0) { continue } @@ -20284,7 +20284,7 @@ func (c *Checker) getSignatureFromDeclaration(declaration *ast.Node) *Signature } var classType *Type if ast.IsConstructorDeclaration(declaration) { - classType = c.getDeclaredTypeOfClassOrInterface(c.getMergedSymbol(declaration.Parent.Symbol())) + classType = c.getDeclaredTypeOfClassOrInterface(c.getMergedSymbol(declaration.Parent().Symbol())) } var typeParameters []*Type if classType != nil { @@ -20298,7 +20298,7 @@ func (c *Checker) getSignatureFromDeclaration(declaration *ast.Node) *Signature if ast.IsConstructorTypeNode(declaration) || ast.IsConstructorDeclaration(declaration) || ast.IsConstructSignatureDeclaration(declaration) { flags |= SignatureFlagsConstruct } - if ast.IsConstructorTypeNode(declaration) && ast.HasSyntacticModifier(declaration, ast.ModifierFlagsAbstract) || ast.IsConstructorDeclaration(declaration) && ast.HasSyntacticModifier(declaration.Parent, ast.ModifierFlagsAbstract) { + if ast.IsConstructorTypeNode(declaration) && ast.HasSyntacticModifier(declaration, ast.ModifierFlagsAbstract) || ast.IsConstructorDeclaration(declaration) && ast.HasSyntacticModifier(declaration.Parent(), ast.ModifierFlagsAbstract) { flags |= SignatureFlagsAbstract } links.resolvedSignature = c.newSignature(flags, declaration, typeParameters, thisParameter, parameters, nil /*resolvedReturnType*/, nil /*resolvedTypePredicate*/, minArgumentCount) @@ -20361,7 +20361,7 @@ func (c *Checker) isLateBindableName(node *ast.Node) bool { if ast.IsComputedPropertyName(node) { return isTypeUsableAsPropertyName(c.checkComputedPropertyName(node)) } - return isTypeUsableAsPropertyName(c.checkExpressionCached(node.AsElementAccessExpression().ArgumentExpression)) + return isTypeUsableAsPropertyName(c.checkExpressionCached(node.AsElementAccessExpression().ArgumentExpression())) } func (c *Checker) hasLateBindableIndexSignature(node *ast.Node) bool { @@ -20376,7 +20376,7 @@ func (c *Checker) isLateBindableIndexSignature(node *ast.Node) bool { if ast.IsComputedPropertyName(node) { return c.isTypeUsableAsIndexSignatureDeclaration(c.checkComputedPropertyName(node)) } - return c.isTypeUsableAsIndexSignatureDeclaration(c.checkExpressionCached(node.AsElementAccessExpression().ArgumentExpression)) + return c.isTypeUsableAsIndexSignatureDeclaration(c.checkExpressionCached(node.AsElementAccessExpression().ArgumentExpression())) } func (c *Checker) isTypeUsableAsIndexSignatureDeclaration(t *Type) bool { @@ -20389,7 +20389,7 @@ func isLateBindableAST(node *ast.Node) bool { case ast.IsComputedPropertyName(node): expr = node.Expression() case ast.IsElementAccessExpression(node): - expr = node.AsElementAccessExpression().ArgumentExpression + expr = node.AsElementAccessExpression().ArgumentExpression() } return expr != nil && ast.IsEntityNameExpression(expr) } @@ -20453,7 +20453,7 @@ func (c *Checker) getNonCircularReturnTypeOfSignature(sig *Signature) *Type { func (c *Checker) getReturnTypeFromAnnotation(declaration *ast.Node) *Type { if ast.IsConstructorDeclaration(declaration) { - return c.getDeclaredTypeOfClassOrInterface(c.getMergedSymbol(declaration.Parent.Symbol())) + return c.getDeclaredTypeOfClassOrInterface(c.getMergedSymbol(declaration.Parent().Symbol())) } returnType := declaration.Type() if returnType != nil { @@ -20466,8 +20466,8 @@ func (c *Checker) getReturnTypeFromAnnotation(declaration *ast.Node) *Type { } func (c *Checker) getSignatureOfFullSignatureType(node *ast.Node) *Signature { - if ast.IsInJSFile(node) && (ast.IsFunctionDeclaration(node) || ast.IsMethodDeclaration(node) || ast.IsFunctionExpressionOrArrowFunction(node)) && node.FunctionLikeData().FullSignature != nil { - return c.getSingleCallSignature(c.getTypeFromTypeNode(node.FunctionLikeData().FullSignature)) + if ast.IsInJSFile(node) && (ast.IsFunctionDeclaration(node) || ast.IsMethodDeclaration(node) || ast.IsFunctionExpressionOrArrowFunction(node)) && node.FunctionLikeData().FullSignature() != nil { + return c.getSingleCallSignature(c.getTypeFromTypeNode(node.FunctionLikeData().FullSignature())) } return nil } @@ -20475,7 +20475,7 @@ func (c *Checker) getSignatureOfFullSignatureType(node *ast.Node) *Signature { func (c *Checker) getParameterTypeOfFullSignature(node *ast.Node, parameter *ast.ParameterDeclarationNode) *Type { if signature := c.getSignatureOfFullSignatureType(node); signature != nil { pos := slices.Index(node.Parameters(), parameter) - if parameter.AsParameterDeclaration().DotDotDotToken != nil { + if parameter.AsParameterDeclaration().DotDotDotToken() != nil { return c.getRestTypeAtPosition(signature, pos, false /*readonly*/) } else { return c.getTypeAtPosition(signature, pos) @@ -20710,7 +20710,7 @@ func mayReturnNever(fn *ast.Node) bool { case ast.KindFunctionExpression, ast.KindArrowFunction: return true case ast.KindMethodDeclaration: - return ast.IsObjectLiteralExpression(fn.Parent) + return ast.IsObjectLiteralExpression(fn.Parent()) } return false } @@ -20727,7 +20727,7 @@ func (c *Checker) checkAndAggregateYieldOperandTypes(fn *ast.Node, checkMode Che } yieldTypes = core.AppendIfUnique(yieldTypes, c.getYieldedTypeOfYieldExpression(yieldExpr, yieldExprType, c.anyType, isAsync)) var nextType *Type - if yieldExpr.AsYieldExpression().AsteriskToken != nil { + if yieldExpr.AsYieldExpression().AsteriskToken() != nil { iterationTypes := c.getIterationTypesOfIterable(yieldExprType, core.IfElse(isAsync, IterationUseAsyncYieldStar, IterationUseYieldStar), yieldExpr.Expression()) nextType = iterationTypes.nextType } else { @@ -20914,7 +20914,7 @@ func (c *Checker) reportWideningErrorsInType(t *Type) bool { // we need to account for property types coming from object literal type normalization in unions valueDeclaration := core.Find(p.Declarations, func(d *ast.Node) bool { valueDeclaration := d.Symbol().ValueDeclaration - return valueDeclaration != nil && valueDeclaration.Parent == t.symbol.ValueDeclaration + return valueDeclaration != nil && valueDeclaration.Parent() == t.symbol.ValueDeclaration }) if valueDeclaration != nil { c.error(valueDeclaration, diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, c.symbolToString(p), c.TypeToString(c.getWidenedType(s))) @@ -20980,8 +20980,8 @@ func (c *Checker) checkIfExpressionRefinesAnyParameter(fn *ast.Node, expr *ast.N func (c *Checker) checkIfExpressionRefinesParameter(fn *ast.Node, expr *ast.Node, param *ast.Node, initType *Type) *Type { antecedent := getFlowNodeOfNode(expr) - if antecedent == nil && ast.IsReturnStatement(expr.Parent) { - antecedent = getFlowNodeOfNode(expr.Parent) + if antecedent == nil && ast.IsReturnStatement(expr.Parent()) { + antecedent = getFlowNodeOfNode(expr.Parent()) } if antecedent == nil { antecedent = &ast.FlowNode{Flags: ast.FlowFlagsStart} @@ -21227,7 +21227,7 @@ func isThislessType(node *ast.Node) bool { ast.KindSymbolKeyword, ast.KindObjectKeyword, ast.KindVoidKeyword, ast.KindUndefinedKeyword, ast.KindNeverKeyword, ast.KindLiteralType: return true case ast.KindArrayType: - return isThislessType(node.AsArrayTypeNode().ElementType) + return isThislessType(node.AsArrayTypeNode().ElementType()) case ast.KindTypeReference: return core.Every(node.TypeArguments(), isThislessType) } @@ -21246,7 +21246,7 @@ func isThislessFunctionLikeDeclaration(node *ast.Node) bool { // A type parameter is thisless if its constraint is thisless, or if it has no constraint. */ func isThislessTypeParameter(node *ast.Node) bool { - constraint := node.AsTypeParameterDeclaration().Constraint + constraint := node.AsTypeParameterDeclaration().Constraint() return constraint == nil || isThislessType(constraint) } @@ -22133,7 +22133,7 @@ func (c *Checker) isMappedTypeGenericIndexedAccess(t *Type) bool { if t.flags&TypeFlagsIndexedAccess != 0 { objectType := t.AsIndexedAccessType().objectType return objectType.objectFlags&ObjectFlagsMapped != 0 && !c.isGenericMappedType(objectType) && c.isGenericIndexType(t.AsIndexedAccessType().indexType) && - getMappedTypeModifiers(objectType)&MappedTypeModifiersExcludeOptional == 0 && objectType.AsMappedType().declaration.NameType == nil + getMappedTypeModifiers(objectType)&MappedTypeModifiersExcludeOptional == 0 && objectType.AsMappedType().declaration.NameType() == nil } return false } @@ -22189,7 +22189,7 @@ func (c *Checker) getApparentTypeOfMappedType(t *Type) *Type { func (c *Checker) getResolvedApparentTypeOfMappedType(t *Type) *Type { target := core.OrElse(t.AsMappedType().target, t) typeVariable := c.getHomomorphicTypeVariable(target) - if typeVariable != nil && target.AsMappedType().declaration.NameType == nil { + if typeVariable != nil && target.AsMappedType().declaration.NameType() == nil { // We have a homomorphic mapped type or an instantiation of a homomorphic mapped type, i.e. a type // of the form { [P in keyof T]: X }. Obtain the modifiers type (the T of the keyof T), and if it is // another generic mapped type, recursively obtain its apparent type. Otherwise, obtain its base @@ -22355,7 +22355,7 @@ func (c *Checker) getTypeArguments(t *Type) []*Type { case ast.KindTypeReference: typeArguments = append(n.OuterTypeParameters(), c.getEffectiveTypeArguments(node, n.LocalTypeParameters())...) case ast.KindArrayType: - typeArguments = []*Type{c.getTypeFromTypeNode(node.AsArrayTypeNode().ElementType)} + typeArguments = []*Type{c.getTypeFromTypeNode(node.AsArrayTypeNode().ElementType())} case ast.KindTupleType: typeArguments = core.Map(node.Elements(), c.getTypeFromTypeNode) default: @@ -22398,7 +22398,7 @@ func (c *Checker) getMinTypeArgumentCount(typeParameters []*Type) int { func (c *Checker) hasTypeParameterDefault(t *Type) bool { return t.symbol != nil && core.Some(t.symbol.Declarations, func(d *ast.Node) bool { - return ast.IsTypeParameterDeclaration(d) && d.AsTypeParameterDeclaration().DefaultType != nil + return ast.IsTypeParameterDeclaration(d) && d.AsTypeParameterDeclaration().DefaultType() != nil }) } @@ -22472,7 +22472,7 @@ func (c *Checker) getResolvedTypeParameterDefault(t *Type) *Type { if t.symbol != nil { defaultDeclaration := core.FirstNonNil(t.symbol.Declarations, func(decl *ast.Node) *ast.Node { if ast.IsTypeParameterDeclaration(decl) { - return decl.AsTypeParameterDeclaration().DefaultType + return decl.AsTypeParameterDeclaration().DefaultType() } return nil }) @@ -22684,7 +22684,7 @@ func (c *Checker) isNonGenericTopLevelType(t *Type) bool { if declaration == nil { declaration = ast.GetDeclarationOfKind(t.alias.symbol, ast.KindJSTypeAliasDeclaration) } - return declaration != nil && ast.FindAncestorOrQuit(declaration.Parent, func(n *ast.Node) ast.FindAncestorResult { + return declaration != nil && ast.FindAncestorOrQuit(declaration.Parent(), func(n *ast.Node) ast.FindAncestorResult { switch n.Kind { case ast.KindSourceFile: return ast.FindAncestorTrue @@ -22892,7 +22892,7 @@ func (c *Checker) isTypeParameterPossiblyReferenced(tp *Type, node *ast.Node) bo return true } case ast.KindTypeQuery: - entityName := node.AsTypeQueryNode().ExprName + entityName := node.AsTypeQueryNode().ExprName() firstIdentifier := ast.GetFirstIdentifier(entityName) if !ast.IsThisIdentifier(firstIdentifier) { firstIdentifierSymbol := c.getResolvedSymbol(firstIdentifier) @@ -22900,7 +22900,7 @@ func (c *Checker) isTypeParameterPossiblyReferenced(tp *Type, node *ast.Node) bo var tpScope *ast.Node switch { case ast.IsTypeParameterDeclaration(tpDeclaration): - tpScope = tpDeclaration.Parent // Type parameter is a regular type parameter, e.g. foo + tpScope = tpDeclaration.Parent() // Type parameter is a regular type parameter, e.g. foo case tp.AsTypeParameter().isThisType: tpScope = tpDeclaration // Type parameter is the this type, and its declaration is the class declaration. } @@ -22924,9 +22924,9 @@ func (c *Checker) isTypeParameterPossiblyReferenced(tp *Type, node *ast.Node) bo // type parameter, or if the node contains type queries that we can't prove couldn't contain references to the type parameter, // we consider the type parameter possibly referenced. if tp.symbol != nil && len(tp.symbol.Declarations) == 1 { - container := tp.symbol.Declarations[0].Parent - for n := node; n != container; n = n.Parent { - if n == nil || ast.IsBlock(n) || ast.IsConditionalTypeNode(n) && containsReference(n.AsConditionalTypeNode().ExtendsType) { + container := tp.symbol.Declarations[0].Parent() + for n := node; n != container; n = n.Parent() { + if n == nil || ast.IsBlock(n) || ast.IsConditionalTypeNode(n) && containsReference(n.AsConditionalTypeNode().ExtendsType()) { return true } } @@ -23031,7 +23031,7 @@ func (c *Checker) instantiateMappedType(t *Type, m *TypeMapper, alias *TypeAlias if s.flags&(TypeFlagsAnyOrUnknown|TypeFlagsInstantiableNonPrimitive|TypeFlagsObject|TypeFlagsIntersection) == 0 || s == c.wildcardType || c.isErrorType(s) { return s } - if d.declaration.NameType == nil { + if d.declaration.NameType() == nil { if c.isArrayType(s) || s.flags&TypeFlagsAny != 0 && c.findResolutionCycleStartIndex(typeVariable, TypeSystemPropertyNameResolvedBaseConstraint) < 0 && c.hasArrayOrTypeTypeConstraint(typeVariable) { return c.instantiateMappedArrayType(s, t, prependTypeMapping(typeVariable, s, m)) } @@ -23150,7 +23150,7 @@ func getModifiedReadonlyState(state bool, modifiers MappedTypeModifiers) bool { func (c *Checker) getTypeParameterFromMappedType(t *Type) *Type { m := t.AsMappedType() if m.typeParameter == nil { - m.typeParameter = c.getDeclaredTypeOfTypeParameter(c.getSymbolOfDeclaration(m.declaration.TypeParameter)) + m.typeParameter = c.getDeclaredTypeOfTypeParameter(c.getSymbolOfDeclaration(m.declaration.TypeParameter())) } return m.typeParameter } @@ -23165,11 +23165,11 @@ func (c *Checker) getConstraintTypeFromMappedType(t *Type) *Type { func (c *Checker) getNameTypeFromMappedType(t *Type) *Type { m := t.AsMappedType() - if m.declaration.NameType == nil { + if m.declaration.NameType() == nil { return nil } if m.nameType == nil { - m.nameType = c.instantiateType(c.getTypeFromTypeNode(m.declaration.NameType), m.mapper) + m.nameType = c.instantiateType(c.getTypeFromTypeNode(m.declaration.NameType()), m.mapper) } return m.nameType } @@ -23177,8 +23177,8 @@ func (c *Checker) getNameTypeFromMappedType(t *Type) *Type { func (c *Checker) getTemplateTypeFromMappedType(t *Type) *Type { m := t.AsMappedType() if m.templateType == nil { - if m.declaration.Type != nil { - m.templateType = c.instantiateType(c.addOptionalityEx(c.getTypeFromTypeNode(m.declaration.Type) /*isProperty*/, true, getMappedTypeModifiers(t)&MappedTypeModifiersIncludeOptional != 0), m.mapper) + if m.declaration.Type() != nil { + m.templateType = c.instantiateType(c.addOptionalityEx(c.getTypeFromTypeNode(m.declaration.Type()) /*isProperty*/, true, getMappedTypeModifiers(t)&MappedTypeModifiersIncludeOptional != 0), m.mapper) } else { m.templateType = c.errorType } @@ -23192,7 +23192,7 @@ func (c *Checker) isMappedTypeWithKeyofConstraintDeclaration(t *Type) bool { } func (c *Checker) getConstraintDeclarationForMappedType(t *Type) *ast.Node { - return t.AsMappedType().declaration.TypeParameter.AsTypeParameterDeclaration().Constraint + return t.AsMappedType().declaration.TypeParameter().AsTypeParameterDeclaration().Constraint() } func (c *Checker) getApparentMappedTypeKeys(nameType *Type, targetType *Type) *Type { @@ -23302,7 +23302,7 @@ func (c *Checker) getTypeFromTypeNodeWorker(node *ast.Node) *Type { return t } case ast.KindJSDocVariadicType: - return c.createArrayType(c.getTypeFromTypeNode(node.AsJSDocVariadicType().Type)) + return c.createArrayType(c.getTypeFromTypeNode(node.AsJSDocVariadicType().Type())) case ast.KindJSDocOptionalType: return c.addOptionality(c.getTypeFromTypeNode(node.Type())) case ast.KindUnknownKeyword: @@ -23336,7 +23336,7 @@ func (c *Checker) getTypeFromTypeNodeWorker(node *ast.Node) *Type { case ast.KindTypeReference, ast.KindExpressionWithTypeArguments: return c.getTypeFromTypeReference(node) case ast.KindTypePredicate: - if node.AsTypePredicateNode().AssertsModifier != nil { + if node.AsTypePredicateNode().AssertsModifier() != nil { return c.voidType } return c.booleanType @@ -23388,7 +23388,7 @@ func (c *Checker) getTypeFromThisTypeNode(node *ast.Node) *Type { func (c *Checker) getThisType(node *ast.Node) *Type { container := ast.GetThisContainer(node /*includeArrowFunctions*/, false /*includeClassComputedPropertyName*/, false) if container != nil { - parent := container.Parent + parent := container.Parent() if parent != nil && (ast.IsClassLike(parent) || ast.IsInterfaceDeclaration(parent)) { if !ast.IsStatic(container) && (!ast.IsConstructorDeclaration(container) || isNodeDescendantOf(node, container.Body())) { return core.Coalesce(c.getDeclaredTypeOfClassOrInterface(c.getSymbolOfDeclaration(parent)).AsInterfaceType().thisType, c.errorType) @@ -23400,12 +23400,12 @@ func (c *Checker) getThisType(node *ast.Node) *Type { } func (c *Checker) getTypeFromLiteralTypeNode(node *ast.Node) *Type { - if node.AsLiteralTypeNode().Literal.Kind == ast.KindNullKeyword { + if node.AsLiteralTypeNode().Literal().Kind == ast.KindNullKeyword { return c.nullType } links := c.typeNodeLinks.Get(node) if links.resolvedType == nil { - links.resolvedType = c.getRegularTypeOfLiteralType(c.checkExpression(node.AsLiteralTypeNode().Literal)) + links.resolvedType = c.getRegularTypeOfLiteralType(c.checkExpression(node.AsLiteralTypeNode().Literal())) } return links.resolvedType } @@ -23429,8 +23429,8 @@ func (c *Checker) getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node *as func (c *Checker) getTypeFromIndexedAccessTypeNode(node *ast.Node) *Type { links := c.typeNodeLinks.Get(node) if links.resolvedType == nil { - objectType := c.getTypeFromTypeNode(node.AsIndexedAccessTypeNode().ObjectType) - indexType := c.getTypeFromTypeNode(node.AsIndexedAccessTypeNode().IndexType) + objectType := c.getTypeFromTypeNode(node.AsIndexedAccessTypeNode().ObjectType()) + indexType := c.getTypeFromTypeNode(node.AsIndexedAccessTypeNode().IndexType()) potentialAlias := c.getAliasForTypeNode(node) links.resolvedType = c.getIndexedAccessTypeEx(objectType, indexType, AccessFlagsNone, node, potentialAlias) } @@ -23446,7 +23446,7 @@ func (c *Checker) getTypeFromTypeOperatorNode(node *ast.Node) *Type { links.resolvedType = c.getIndexType(c.getTypeFromTypeNode(argType)) case ast.KindUniqueKeyword: if argType.Kind == ast.KindSymbolKeyword { - links.resolvedType = c.getESSymbolLikeTypeForNode(ast.WalkUpParenthesizedTypes(node.Parent)) + links.resolvedType = c.getESSymbolLikeTypeForNode(ast.WalkUpParenthesizedTypes(node.Parent())) } else { links.resolvedType = c.errorType } @@ -23486,8 +23486,8 @@ func (c *Checker) getTypeFromTypeReference(node *ast.Node) *Type { // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the // type reference in checkTypeReferenceNode. // handle LS queries on the `const` in `x as const` by resolving to the type of `x` - if isConstTypeReference(node) && ast.IsAssertionExpression(node.Parent) { - links.resolvedType = c.checkExpressionCached(node.Parent.Expression()) + if isConstTypeReference(node) && ast.IsAssertionExpression(node.Parent()) { + links.resolvedType = c.checkExpressionCached(node.Parent().Expression()) } else if t := c.getIntendedTypeFromJSDocTypeReference(node); t != nil { links.resolvedType = t } else { @@ -23499,9 +23499,9 @@ func (c *Checker) getTypeFromTypeReference(node *ast.Node) *Type { func (c *Checker) getDistributedTypeParameter(node *ast.Node, t *Type) *Type { if t.flags&TypeFlagsTypeParameter != 0 && !t.AsTypeParameter().isDistributed { - for n := node.Parent; n != nil && !ast.IsStatement(n); n = n.Parent { + for n := node.Parent(); n != nil && !ast.IsStatement(n); n = n.Parent() { if ast.IsConditionalTypeNode(n) { - if checkTypeNode := n.AsConditionalTypeNode().CheckType; isSimpleIdentifierTypeReference(checkTypeNode) && c.getSymbolFromTypeReference(checkTypeNode) == t.symbol { + if checkTypeNode := n.AsConditionalTypeNode().CheckType(); isSimpleIdentifierTypeReference(checkTypeNode) && c.getSymbolFromTypeReference(checkTypeNode) == t.symbol { // If node is contained in a distributive conditional type for the given type parameter, // return the distributed form of the type parameter. return c.getDistributedTypeFromTypeParameter(t) @@ -23530,12 +23530,12 @@ func getNonDistributedTypeParameter(t *Type) *Type { } func isSimpleIdentifierTypeReference(node *ast.Node) bool { - return ast.IsTypeReferenceNode(node) && ast.IsIdentifier(node.AsTypeReferenceNode().TypeName) && node.TypeArgumentList() == nil + return ast.IsTypeReferenceNode(node) && ast.IsIdentifier(node.AsTypeReferenceNode().TypeName()) && node.TypeArgumentList() == nil } func (c *Checker) getIntendedTypeFromJSDocTypeReference(node *ast.Node) *Type { if node.Flags&ast.NodeFlagsJSDoc != 0 && ast.IsTypeReferenceNode(node) { - typeName := node.AsTypeReferenceNode().TypeName + typeName := node.AsTypeReferenceNode().TypeName() if ast.IsIdentifier(typeName) { typeArgs := node.TypeArguments() switch typeName.Text() { @@ -23619,7 +23619,7 @@ func (c *Checker) getUnresolvedSymbolForEntityName(name *ast.Node) *ast.Symbol { var identifier *ast.Node switch name.Kind { case ast.KindQualifiedName: - identifier = name.AsQualifiedName().Right + identifier = name.AsQualifiedName().Right() case ast.KindPropertyAccessExpression: identifier = name.Name() default: @@ -23630,7 +23630,7 @@ func (c *Checker) getUnresolvedSymbolForEntityName(name *ast.Node) *ast.Symbol { var parentSymbol *ast.Symbol switch name.Kind { case ast.KindQualifiedName: - parentSymbol = c.getUnresolvedSymbolForEntityName(name.AsQualifiedName().Left) + parentSymbol = c.getUnresolvedSymbolForEntityName(name.AsQualifiedName().Left()) case ast.KindPropertyAccessExpression: parentSymbol = c.getUnresolvedSymbolForEntityName(name.Expression()) } @@ -23694,7 +23694,7 @@ func (c *Checker) getTypeFromClassOrInterfaceReference(node *ast.Node, symbol *a if !isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > len(typeParameters)) { var message *diagnostics.Message - missingAugmentsTag := isJs && ast.IsExpressionWithTypeArguments(node) && !ast.IsJSDocAugmentsTag(node.Parent) + missingAugmentsTag := isJs && ast.IsExpressionWithTypeArguments(node) && !ast.IsJSDocAugmentsTag(node.Parent()) if missingAugmentsTag { message = diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag if minTypeArgumentCount < len(typeParameters) { @@ -23739,7 +23739,7 @@ func (c *Checker) checkNoTypeArguments(node *ast.Node, symbol *ast.Symbol) bool if symbol != nil { typeName = c.symbolToString(symbol) } else { - typeName = scanner.DeclarationNameToString(node.AsTypeReferenceNode().TypeName) + typeName = scanner.DeclarationNameToString(node.AsTypeReferenceNode().TypeName()) } c.error(node, diagnostics.Type_0_is_not_generic, typeName) return false @@ -23756,7 +23756,7 @@ func (c *Checker) isDeferredTypeReferenceNode(node *ast.Node, hasDefaultTypeArgu if c.isResolvedByTypeAlias(node) { switch node.Kind { case ast.KindArrayType: - return c.mayResolveTypeAlias(node.AsArrayTypeNode().ElementType) + return c.mayResolveTypeAlias(node.AsArrayTypeNode().ElementType()) case ast.KindTupleType: return core.Some(node.Elements(), c.mayResolveTypeAlias) case ast.KindTypeReference: @@ -23771,7 +23771,7 @@ func (c *Checker) isDeferredTypeReferenceNode(node *ast.Node, hasDefaultTypeArgu // resolve their constituent types. We include SyntaxKind.TypeReference because type arguments // of type aliases are eagerly resolved. func (c *Checker) isResolvedByTypeAlias(node *ast.Node) bool { - parent := node.Parent + parent := node.Parent() switch parent.Kind { case ast.KindParenthesizedType, ast.KindNamedTupleMember, ast.KindTypeReference, ast.KindUnionType, ast.KindIntersectionType, ast.KindIndexedAccessType, ast.KindConditionalType, ast.KindTypeOperator, ast.KindArrayType, ast.KindTupleType: @@ -23795,16 +23795,16 @@ func (c *Checker) mayResolveTypeAlias(node *ast.Node) bool { case ast.KindParenthesizedType, ast.KindOptionalType, ast.KindNamedTupleMember: return c.mayResolveTypeAlias(node.Type()) case ast.KindRestType: - return node.Type().Kind != ast.KindArrayType || c.mayResolveTypeAlias(node.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) + return core.Some(node.AsUnionTypeNode().Types().Nodes, c.mayResolveTypeAlias) case ast.KindIntersectionType: - return core.Some(node.AsIntersectionTypeNode().Types.Nodes, c.mayResolveTypeAlias) + return core.Some(node.AsIntersectionTypeNode().Types().Nodes, c.mayResolveTypeAlias) case ast.KindIndexedAccessType: - return c.mayResolveTypeAlias(node.AsIndexedAccessTypeNode().ObjectType) || c.mayResolveTypeAlias(node.AsIndexedAccessTypeNode().IndexType) + return c.mayResolveTypeAlias(node.AsIndexedAccessTypeNode().ObjectType()) || c.mayResolveTypeAlias(node.AsIndexedAccessTypeNode().IndexType()) case ast.KindConditionalType: - return c.mayResolveTypeAlias(node.AsConditionalTypeNode().CheckType) || c.mayResolveTypeAlias(node.AsConditionalTypeNode().ExtendsType) || - c.mayResolveTypeAlias(node.AsConditionalTypeNode().TrueType) || c.mayResolveTypeAlias(node.AsConditionalTypeNode().FalseType) + return c.mayResolveTypeAlias(node.AsConditionalTypeNode().CheckType()) || c.mayResolveTypeAlias(node.AsConditionalTypeNode().ExtendsType()) || + c.mayResolveTypeAlias(node.AsConditionalTypeNode().TrueType()) || c.mayResolveTypeAlias(node.AsConditionalTypeNode().FalseType()) } return false } @@ -24212,7 +24212,7 @@ func (c *Checker) tryGetDeclaredTypeOfSymbol(symbol *ast.Symbol) *Type { func getTypeReferenceName(node *ast.Node) *ast.Node { switch node.Kind { case ast.KindTypeReference: - return node.AsTypeReferenceNode().TypeName + return node.AsTypeReferenceNode().TypeName() case ast.KindExpressionWithTypeArguments: // We only support expressions that are simple qualified names. For other // expressions this produces nil @@ -24233,9 +24233,9 @@ func (c *Checker) getAliasForTypeNode(node *ast.Node) *TypeAlias { } func (c *Checker) getAliasSymbolForTypeNode(node *ast.Node) *ast.Symbol { - host := node.Parent + host := node.Parent() for ast.IsParenthesizedTypeNode(host) || ast.IsTypeOperatorNode(host) && host.AsTypeOperatorNode().Operator == ast.KindReadonlyKeyword { - host = host.Parent + host = host.Parent() } if isTypeAlias(host) { return c.getSymbolOfDeclaration(host) @@ -24280,7 +24280,7 @@ func (c *Checker) canGetTypeParametersOfClassOrInterface(symbol *ast.Symbol) boo // Return the outer type parameters of a node or undefined if the node has no outer type parameters. func (c *Checker) getOuterTypeParameters(node *ast.Node, includeThisTypes bool) []*Type { for { - node = node.Parent + node = node.Parent() if node == nil { return nil } @@ -24298,7 +24298,7 @@ func (c *Checker) getOuterTypeParameters(node *ast.Node, includeThisTypes bool) } } if kind == ast.KindMappedType { - return append(outerTypeParameters, c.getDeclaredTypeOfTypeParameter(c.getSymbolOfDeclaration(node.AsMappedTypeNode().TypeParameter))) + return append(outerTypeParameters, c.getDeclaredTypeOfTypeParameter(c.getSymbolOfDeclaration(node.AsMappedTypeNode().TypeParameter()))) } if kind == ast.KindConditionalType { return append(outerTypeParameters, c.getInferTypeParameters(node)...) @@ -24436,7 +24436,7 @@ func (c *Checker) getDeclaredTypeOfEnum(symbol *ast.Symbol) *Type { } func (c *Checker) getEnumMemberValue(node *ast.Node) evaluator.Result { - c.computeEnumMemberValues(node.Parent) + c.computeEnumMemberValues(node.Parent()) return c.enumMemberLinks.Get(node).value } @@ -24497,7 +24497,7 @@ func (c *Checker) computeEnumMemberValue(member *ast.Node, autoValue *jsnum.Numb } // In ambient non-const numeric enum declarations, enum members without initializers are // considered computed members (as opposed to having auto-incremented values). - if member.Parent.Flags&ast.NodeFlagsAmbient != 0 && !ast.IsEnumConst(member.Parent) { + if member.Parent().Flags&ast.NodeFlagsAmbient != 0 && !ast.IsEnumConst(member.Parent()) { return evaluator.NewResult(nil, false, false, false) } // If the member declaration specifies no value, the member is considered a constant enum member. @@ -24519,7 +24519,7 @@ func (c *Checker) computeEnumMemberValue(member *ast.Node, autoValue *jsnum.Numb } func (c *Checker) computeConstantEnumMemberValue(member *ast.Node) evaluator.Result { - isConstEnum := ast.IsEnumConst(member.Parent) + isConstEnum := ast.IsEnumConst(member.Parent()) initializer := member.Initializer() result := c.evaluate(initializer, member) switch { @@ -24533,13 +24533,13 @@ func (c *Checker) computeConstantEnumMemberValue(member *ast.Node) evaluator.Res } if c.compilerOptions.GetIsolatedModules() { if _, isString := result.Value.(string); isString && !result.IsSyntacticallyString { - memberName := member.Parent.Name().Text() + "." + member.Name().Text() + memberName := member.Parent().Name().Text() + "." + member.Name().Text() c.error(initializer, diagnostics.X_0_has_a_string_type_but_must_have_syntactically_recognizable_string_syntax_when_isolatedModules_is_enabled, memberName) } } case isConstEnum: c.error(initializer, diagnostics.X_const_enum_member_initializers_must_be_constant_expressions) - case member.Parent.Flags&ast.NodeFlagsAmbient != 0: + case member.Parent().Flags&ast.NodeFlagsAmbient != 0: c.error(initializer, diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression) default: c.checkTypeAssignableTo(c.checkExpression(initializer), c.numberType, initializer, diagnostics.Type_0_is_not_assignable_to_type_1_as_required_for_computed_enum_member_values) @@ -24582,10 +24582,10 @@ func (c *Checker) evaluateEntity(expr *ast.Node, location *ast.Node) evaluator.R return evaluator.NewResult(nil, false, false, false) case ast.KindElementAccessExpression: root := expr.Expression() - if ast.IsEntityNameExpression(root) && ast.IsStringLiteralLike(expr.AsElementAccessExpression().ArgumentExpression) { + if ast.IsEntityNameExpression(root) && ast.IsStringLiteralLike(expr.AsElementAccessExpression().ArgumentExpression()) { rootSymbol := c.resolveEntityName(root, ast.SymbolFlagsValue, true /*ignoreErrors*/, false, nil) if rootSymbol != nil && rootSymbol.Flags&ast.SymbolFlagsEnum != 0 { - name := expr.AsElementAccessExpression().ArgumentExpression.Text() + name := expr.AsElementAccessExpression().ArgumentExpression().Text() member := rootSymbol.Exports[name] if member != nil { if location != nil { @@ -24611,7 +24611,7 @@ func (c *Checker) evaluateEnumMember(expr *ast.Node, symbol *ast.Symbol, locatio return evaluator.NewResult(jsnum.Number(0), false, false, false) } value := c.getEnumMemberValue(declaration) - if location.Parent != declaration.Parent { + if location.Parent() != declaration.Parent() { return evaluator.NewResult(value.Value, value.IsSyntacticallyString, value.ResolvedOtherFiles, true /*hasExternalReferences*/) } return value @@ -24653,7 +24653,7 @@ func (c *Checker) getTypeFromArrayOrTupleTypeNode(node *ast.Node) *Type { } else { var elementTypes []*Type if node.Kind == ast.KindArrayType { - elementTypes = []*Type{c.getTypeFromTypeNode(node.AsArrayTypeNode().ElementType)} + elementTypes = []*Type{c.getTypeFromTypeNode(node.AsArrayTypeNode().ElementType())} } else { elementTypes = core.Map(node.Elements(), c.getTypeFromTypeNode) } @@ -24672,7 +24672,7 @@ func (c *Checker) isVariadicTupleElement(node *ast.Node) bool { } func (c *Checker) getArrayOrTupleTargetType(node *ast.Node) *Type { - readonly := c.isReadonlyTypeOperator(node.Parent) + readonly := c.isReadonlyTypeOperator(node.Parent()) elementType := c.getArrayElementTypeNode(node) if elementType != nil { if readonly { @@ -24690,7 +24690,7 @@ func (c *Checker) isReadonlyTypeOperator(node *ast.Node) bool { func (c *Checker) getTypeFromNamedTupleTypeNode(node *ast.Node) *Type { links := c.typeNodeLinks.Get(node) if links.resolvedType == nil { - if node.AsNamedTupleMember().DotDotDotToken != nil { + if node.AsNamedTupleMember().DotDotDotToken() != nil { links.resolvedType = c.getTypeFromRestTypeNode(node) } else { links.resolvedType = c.addOptionalityEx(c.getTypeFromTypeNode(node.Type()), true /*isProperty*/, node.QuestionToken() != nil) @@ -24718,12 +24718,12 @@ func (c *Checker) getArrayElementTypeNode(node *ast.Node) *ast.Node { if node.Kind == ast.KindRestType { return c.getArrayElementTypeNode(node.Type()) } - if node.Kind == ast.KindNamedTupleMember && node.AsNamedTupleMember().DotDotDotToken != nil { + if node.Kind == ast.KindNamedTupleMember && node.AsNamedTupleMember().DotDotDotToken() != nil { return c.getArrayElementTypeNode(node.Type()) } } case ast.KindArrayType: - return node.AsArrayTypeNode().ElementType + return node.AsArrayTypeNode().ElementType() } return nil } @@ -24736,7 +24736,7 @@ func (c *Checker) getTypeFromUnionTypeNode(node *ast.Node) *Type { links := c.typeNodeLinks.Get(node) if links.resolvedType == nil { alias := c.getAliasForTypeNode(node) - links.resolvedType = c.getUnionTypeEx(core.Map(node.AsUnionTypeNode().Types.Nodes, c.getTypeFromTypeNode), UnionReductionLiteral, alias, nil /*origin*/) + links.resolvedType = c.getUnionTypeEx(core.Map(node.AsUnionTypeNode().Types().Nodes, c.getTypeFromTypeNode), UnionReductionLiteral, alias, nil /*origin*/) } return links.resolvedType } @@ -24745,7 +24745,7 @@ func (c *Checker) getTypeFromIntersectionTypeNode(node *ast.Node) *Type { links := c.typeNodeLinks.Get(node) if links.resolvedType == nil { alias := c.getAliasForTypeNode(node) - types := core.Map(node.AsIntersectionTypeNode().Types.Nodes, c.getTypeFromTypeNode) + types := core.Map(node.AsIntersectionTypeNode().Types().Nodes, c.getTypeFromTypeNode) // We perform no supertype reduction for X & {} or {} & X, where X is one of string, number, bigint, // or a pattern literal template type. This enables union types like "a" | "b" | string & {} or // "aa" | "ab" | `a${string}` which preserve the literal types for purposes of statement completion. @@ -24765,12 +24765,12 @@ func (c *Checker) getTypeFromIntersectionTypeNode(node *ast.Node) *Type { func (c *Checker) getTypeFromTemplateTypeNode(node *ast.Node) *Type { links := c.typeNodeLinks.Get(node) if links.resolvedType == nil { - spans := node.AsTemplateLiteralTypeNode().TemplateSpans + spans := node.AsTemplateLiteralTypeNode().TemplateSpans() texts := make([]string, len(spans.Nodes)+1) types := make([]*Type, len(spans.Nodes)) - texts[0] = node.AsTemplateLiteralTypeNode().Head.Text() + texts[0] = node.AsTemplateLiteralTypeNode().Head().Text() for i, span := range spans.Nodes { - texts[i+1] = span.AsTemplateLiteralTypeSpan().Literal.Text() + texts[i+1] = span.AsTemplateLiteralTypeSpan().Literal().Text() types[i] = c.getTypeFromTypeNode(span.Type()) } links.resolvedType = c.getTemplateLiteralType(texts, types) @@ -24795,7 +24795,7 @@ func (c *Checker) getTypeFromMappedTypeNode(node *ast.Node) *Type { func (c *Checker) getTypeFromConditionalTypeNode(node *ast.Node) *Type { links := c.typeNodeLinks.Get(node) if links.resolvedType == nil { - checkType := c.getTypeFromTypeNode(node.AsConditionalTypeNode().CheckType) + checkType := c.getTypeFromTypeNode(node.AsConditionalTypeNode().CheckType()) alias := c.getAliasForTypeNode(node) allOuterTypeParameters := c.getOuterTypeParameters(node, true /*includeThisTypes*/) var outerTypeParameters []*Type @@ -24807,7 +24807,7 @@ func (c *Checker) getTypeFromConditionalTypeNode(node *ast.Node) *Type { root := &ConditionalRoot{ node: node.AsConditionalTypeNode(), checkType: checkType, - extendsType: c.getTypeFromTypeNode(node.AsConditionalTypeNode().ExtendsType), + extendsType: c.getTypeFromTypeNode(node.AsConditionalTypeNode().ExtendsType()), isDistributive: checkType.flags&TypeFlagsTypeParameter != 0, inferTypeParameters: c.getInferTypeParameters(node), outerTypeParameters: outerTypeParameters, @@ -24845,8 +24845,8 @@ func (c *Checker) getConditionalType(root *ConditionalRoot, mapper *TypeMapper, if checkType == c.wildcardType || extendsType == c.wildcardType { return c.wildcardType } - checkTypeNode := ast.SkipTypeParentheses(root.node.CheckType) - extendsTypeNode := ast.SkipTypeParentheses(root.node.ExtendsType) + checkTypeNode := ast.SkipTypeParentheses(root.node.CheckType()) + extendsTypeNode := ast.SkipTypeParentheses(root.node.ExtendsType()) // 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 ? ...`. @@ -24909,14 +24909,14 @@ func (c *Checker) getConditionalType(root *ConditionalRoot, mapper *TypeMapper, if checkType.flags&TypeFlagsAny != 0 || forConstraint && inferredExtendsType.flags&TypeFlagsNever == 0 && someType(c.getPermissiveInstantiation(inferredExtendsType), func(t *Type) bool { return c.isTypeAssignableTo(t, c.getPermissiveInstantiation(checkType)) }) { - extraTypes = append(extraTypes, c.instantiateType(c.getTypeFromTypeNode(root.node.TrueType), core.OrElse(combinedMapper, mapper))) + extraTypes = append(extraTypes, c.instantiateType(c.getTypeFromTypeNode(root.node.TrueType()), core.OrElse(combinedMapper, mapper))) } // If falseType is an immediately nested conditional type that isn't distributive or has an // identical checkType, switch to that type and loop. - falseType := c.getTypeFromTypeNode(root.node.FalseType) + falseType := c.getTypeFromTypeNode(root.node.FalseType()) if falseType.flags&TypeFlagsConditional != 0 { newRoot := falseType.AsConditionalType().root - if newRoot.node.Parent == root.node.AsNode() && (!newRoot.isDistributive || newRoot.checkType == root.checkType) { + if newRoot.node.Parent() == root.node.AsNode() && (!newRoot.isDistributive || newRoot.checkType == root.checkType) { root = newRoot continue } @@ -24939,7 +24939,7 @@ func (c *Checker) getConditionalType(root *ConditionalRoot, mapper *TypeMapper, // type Foo = T extends { x: string } ? string : number // doesn't immediately resolve to 'string' instead of being deferred. if inferredExtendsType.flags&TypeFlagsAnyOrUnknown != 0 || c.isTypeAssignableTo(c.getRestrictiveInstantiation(checkType), c.getRestrictiveInstantiation(inferredExtendsType)) { - trueType := c.getTypeFromTypeNode(root.node.TrueType) + trueType := c.getTypeFromTypeNode(root.node.TrueType()) trueMapper := core.OrElse(combinedMapper, mapper) if newRoot, newRootMapper := c.getTailRecursionRoot(trueType, trueMapper); newRoot != nil { root = newRoot @@ -24994,7 +24994,7 @@ func (c *Checker) getTailRecursionRoot(newType *Type, newMapper *TypeMapper) (*C func (c *Checker) isSimpleTupleType(node *ast.Node) bool { 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) + return ast.IsOptionalTypeNode(e) || ast.IsRestTypeNode(e) || ast.IsNamedTupleMember(e) && (e.QuestionToken() != nil || e.AsNamedTupleMember().DotDotDotToken() != nil) }) } @@ -25065,7 +25065,7 @@ func (c *Checker) permissiveMapperWorker(t *Type) *Type { func (c *Checker) getTrueTypeFromConditionalType(t *Type) *Type { d := t.AsConditionalType() if d.resolvedTrueType == nil { - d.resolvedTrueType = c.instantiateType(c.getTypeFromTypeNode(d.root.node.TrueType), d.mapper) + d.resolvedTrueType = c.instantiateType(c.getTypeFromTypeNode(d.root.node.TrueType()), d.mapper) } return d.resolvedTrueType } @@ -25073,7 +25073,7 @@ func (c *Checker) getTrueTypeFromConditionalType(t *Type) *Type { func (c *Checker) getFalseTypeFromConditionalType(t *Type) *Type { d := t.AsConditionalType() if d.resolvedFalseType == nil { - d.resolvedFalseType = c.instantiateType(c.getTypeFromTypeNode(d.root.node.FalseType), d.mapper) + d.resolvedFalseType = c.instantiateType(c.getTypeFromTypeNode(d.root.node.FalseType()), d.mapper) } return d.resolvedFalseType } @@ -25082,7 +25082,7 @@ func (c *Checker) getInferredTrueTypeFromConditionalType(t *Type) *Type { d := t.AsConditionalType() if d.resolvedInferredTrueType == nil { if d.combinedMapper != nil { - d.resolvedInferredTrueType = c.instantiateType(c.getTypeFromTypeNode(d.root.node.TrueType), d.combinedMapper) + d.resolvedInferredTrueType = c.instantiateType(c.getTypeFromTypeNode(d.root.node.TrueType()), d.combinedMapper) } else { d.resolvedInferredTrueType = c.getTrueTypeFromConditionalType(t) } @@ -25093,7 +25093,7 @@ func (c *Checker) getInferredTrueTypeFromConditionalType(t *Type) *Type { func (c *Checker) getTypeFromInferTypeNode(node *ast.Node) *Type { links := c.typeNodeLinks.Get(node) if links.resolvedType == nil { - links.resolvedType = c.getDeclaredTypeOfTypeParameter(c.getSymbolOfDeclaration(node.AsInferTypeNode().TypeParameter)) + links.resolvedType = c.getDeclaredTypeOfTypeParameter(c.getSymbolOfDeclaration(node.AsInferTypeNode().TypeParameter())) } return links.resolvedType } @@ -25103,22 +25103,22 @@ func (c *Checker) getTypeFromImportTypeNode(node *ast.Node) *Type { if links.resolvedType == nil { n := node.AsImportTypeNode() if !ast.IsLiteralImportTypeNode(node) { - c.error(n.Argument, diagnostics.String_literal_expected) + c.error(n.Argument(), diagnostics.String_literal_expected) c.symbolNodeLinks.Get(node).resolvedSymbol = c.unknownSymbol links.resolvedType = c.errorType return links.resolvedType } targetMeaning := core.IfElse(n.IsTypeOf, ast.SymbolFlagsValue, ast.SymbolFlagsType) // TODO: Future work: support unions/generics/whatever via a deferred import-type - innerModuleSymbol := c.resolveExternalModuleName(node, n.Argument.AsLiteralTypeNode().Literal, false /*ignoreErrors*/, c.getTypeFromImportAttributes(ast.GetImportAttributes(node))) + innerModuleSymbol := c.resolveExternalModuleName(node, n.Argument().AsLiteralTypeNode().Literal(), false /*ignoreErrors*/, c.getTypeFromImportAttributes(ast.GetImportAttributes(node))) if innerModuleSymbol == nil { c.symbolNodeLinks.Get(node).resolvedSymbol = c.unknownSymbol links.resolvedType = c.errorType return links.resolvedType } moduleSymbol := c.resolveExternalModuleSymbol(innerModuleSymbol, false /*dontResolveAlias*/) - if !ast.NodeIsMissing(n.Qualifier) { - nameChain := c.getIdentifierChain(n.Qualifier) + if !ast.NodeIsMissing(n.Qualifier()) { + nameChain := c.getIdentifierChain(n.Qualifier()) currentNamespace := moduleSymbol for i, current := range nameChain { meaning := ast.SymbolFlagsNamespace @@ -25153,7 +25153,7 @@ func (c *Checker) getTypeFromImportTypeNode(node *ast.Node) *Type { return links.resolvedType } c.symbolNodeLinks.Get(current).resolvedSymbol = next - c.symbolNodeLinks.Get(current.Parent).resolvedSymbol = next + c.symbolNodeLinks.Get(current.Parent()).resolvedSymbol = next currentNamespace = next } links.resolvedType = c.resolveImportSymbolType(node, currentNamespace, targetMeaning) @@ -25164,7 +25164,7 @@ func (c *Checker) getTypeFromImportTypeNode(node *ast.Node) *Type { message := core.IfElse(targetMeaning == ast.SymbolFlagsValue, diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here, diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0) - c.error(node, message, n.Argument.AsLiteralTypeNode().Literal.Text()) + c.error(node, message, n.Argument().AsLiteralTypeNode().Literal().Text()) c.symbolNodeLinks.Get(node).resolvedSymbol = c.unknownSymbol links.resolvedType = c.errorType } @@ -25177,7 +25177,7 @@ func (c *Checker) getIdentifierChain(node *ast.Node) []*ast.Node { if ast.IsIdentifier(node) { return []*ast.Node{node} } - return append(c.getIdentifierChain(node.AsQualifiedName().Left), node.AsQualifiedName().Right) + return append(c.getIdentifierChain(node.AsQualifiedName().Left()), node.AsQualifiedName().Right()) } func (c *Checker) resolveImportSymbolType(node *ast.Node, symbol *ast.Symbol, meaning ast.SymbolFlags) *Type { @@ -25241,10 +25241,10 @@ func (c *Checker) getTupleElementFlags(node *ast.Node) ElementFlags { case ast.KindNamedTupleMember: named := node.AsNamedTupleMember() switch { - case named.QuestionToken != nil: + case named.QuestionToken() != nil: return ElementFlagsOptional - case named.DotDotDotToken != nil: - return core.IfElse(c.getArrayElementTypeNode(named.Type) != nil, ElementFlagsRest, ElementFlagsVariadic) + case named.DotDotDotToken() != nil: + return core.IfElse(c.getArrayElementTypeNode(named.Type()) != nil, ElementFlagsRest, ElementFlagsVariadic) } return ElementFlagsRequired } @@ -25479,7 +25479,7 @@ func (c *Checker) getConditionalFlowTypeOfType(t *Type, node *ast.Node) *Type { var constraints []*Type covariant := true for node != nil && !ast.IsStatement(node) && node.Kind != ast.KindJSDoc { - parent := node.Parent + parent := node.Parent() // only consider variance flipped by parameter locations - `keyof` types would usually be considered variance inverting, but // often get used in indexed accesses where they behave sortof invariantly, but our checking is lax if ast.IsParameterDeclaration(parent) { @@ -25487,12 +25487,12 @@ func (c *Checker) getConditionalFlowTypeOfType(t *Type, node *ast.Node) *Type { } // Always substitute on type parameters, regardless of variance, since even // in contravariant positions, they may rely on substituted constraints to be valid - if (covariant || t.flags&TypeFlagsTypeVariable != 0) && ast.IsConditionalTypeNode(parent) && node == parent.AsConditionalTypeNode().TrueType { - constraint := c.getImpliedConstraint(t, parent.AsConditionalTypeNode().CheckType, parent.AsConditionalTypeNode().ExtendsType) + if (covariant || t.flags&TypeFlagsTypeVariable != 0) && ast.IsConditionalTypeNode(parent) && node == parent.AsConditionalTypeNode().TrueType() { + constraint := c.getImpliedConstraint(t, parent.AsConditionalTypeNode().CheckType(), parent.AsConditionalTypeNode().ExtendsType()) if constraint != nil { constraints = append(constraints, constraint) } - } else if t.flags&TypeFlagsTypeParameter != 0 && ast.IsMappedTypeNode(parent) && parent.AsMappedTypeNode().NameType == nil && node == parent.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) @@ -27320,9 +27320,9 @@ func (c *Checker) isKeyTypeIncluded(keyType *Type, include TypeFlags) bool { } func isInvalidComputedPropertyName(node *ast.Node) bool { - return (ast.IsTypeLiteralNode(node.Parent.Parent) || ast.IsClassLike(node.Parent.Parent) || ast.IsInterfaceDeclaration(node.Parent.Parent)) && - ast.IsBinaryExpression(node.Expression()) && node.Expression().AsBinaryExpression().OperatorToken.Kind == ast.KindInKeyword && - !ast.IsAccessor(node.Parent) + return (ast.IsTypeLiteralNode(node.Parent().Parent()) || ast.IsClassLike(node.Parent().Parent()) || ast.IsInterfaceDeclaration(node.Parent().Parent())) && + ast.IsBinaryExpression(node.Expression()) && node.Expression().AsBinaryExpression().OperatorToken().Kind == ast.KindInKeyword && + !ast.IsAccessor(node.Parent()) } func (c *Checker) checkComputedPropertyName(node *ast.Node) *Type { @@ -27548,9 +27548,9 @@ func (c *Checker) getPropertyTypeForIndexType(originalObjectType *Type, objectTy if accessFlags&AccessFlagsReportDeprecated != 0 && accessNode != nil && len(prop.Declarations) != 0 && c.isDeprecatedSymbol(prop) && c.isUncalledFunctionReference(accessNode, prop) { var deprecatedNode *ast.Node if accessExpression != nil { - deprecatedNode = accessExpression.AsElementAccessExpression().ArgumentExpression + deprecatedNode = accessExpression.AsElementAccessExpression().ArgumentExpression() } else if ast.IsIndexedAccessTypeNode(accessNode) { - deprecatedNode = accessNode.AsIndexedAccessTypeNode().IndexType + deprecatedNode = accessNode.AsIndexedAccessTypeNode().IndexType() } else { deprecatedNode = accessNode } @@ -27559,7 +27559,7 @@ func (c *Checker) getPropertyTypeForIndexType(originalObjectType *Type, objectTy if accessExpression != nil { c.markPropertyAsReferenced(prop, accessExpression, c.isSelfTypeAccess(accessExpression.Expression(), objectType.symbol)) if c.isAssignmentToReadonlyEntity(accessExpression, prop, getAssignmentTargetKind(accessExpression)) { - c.error(accessExpression.AsElementAccessExpression().ArgumentExpression, diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, c.symbolToString(prop)) + c.error(accessExpression.AsElementAccessExpression().ArgumentExpression(), diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, c.symbolToString(prop)) return nil } if accessFlags&AccessFlagsCacheSymbol != 0 { @@ -27673,16 +27673,16 @@ func (c *Checker) getPropertyTypeForIndexType(originalObjectType *Type, objectTy } else if c.noImplicitAny && accessFlags&AccessFlagsSuppressNoImplicitAnyError == 0 { if hasPropName && c.typeHasStaticProperty(propName, objectType) { typeName := c.TypeToString(objectType) - c.error(accessExpression, diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead, propName /* as string */, typeName, typeName+"["+scanner.GetTextOfNode(accessExpression.AsElementAccessExpression().ArgumentExpression)+"]") + c.error(accessExpression, diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead, propName /* as string */, typeName, typeName+"["+scanner.GetTextOfNode(accessExpression.AsElementAccessExpression().ArgumentExpression())+"]") } else if c.getIndexTypeOfType(objectType, c.numberType) != nil { - c.error(accessExpression.AsElementAccessExpression().ArgumentExpression, diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number) + c.error(accessExpression.AsElementAccessExpression().ArgumentExpression(), diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number) } else { var suggestion string if hasPropName { suggestion = c.getSuggestionForNonexistentProperty(propName, objectType) } if suggestion != "" { - c.error(accessExpression.AsElementAccessExpression().ArgumentExpression, diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName /* as string */, c.TypeToString(objectType), suggestion) + c.error(accessExpression.AsElementAccessExpression().ArgumentExpression(), diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName /* as string */, c.TypeToString(objectType), suggestion) } else { suggestion = c.getSuggestionForNonexistentIndexSignature(objectType, accessExpression, indexType) if suggestion != "" { @@ -27783,9 +27783,9 @@ func (c *Checker) getSuggestedTypeForNonexistentStringLiteralType(source *Type, func getIndexNodeForAccessExpression(accessNode *ast.Node) *ast.Node { switch accessNode.Kind { case ast.KindElementAccessExpression: - return accessNode.AsElementAccessExpression().ArgumentExpression + return accessNode.AsElementAccessExpression().ArgumentExpression() case ast.KindIndexedAccessType: - return accessNode.AsIndexedAccessTypeNode().IndexType + return accessNode.AsIndexedAccessTypeNode().IndexType() case ast.KindComputedPropertyName: return accessNode.Expression() } @@ -27827,9 +27827,9 @@ func (c *Checker) isAssignmentToReadonlyEntity(expr *ast.Node, symbol *ast.Symbo } if symbol.ValueDeclaration != nil { isAssignmentDeclaration := ast.IsBinaryExpression(symbol.ValueDeclaration) - isLocalPropertyDeclaration := ctor.Parent == symbol.ValueDeclaration.Parent - isLocalParameterProperty := ctor == symbol.ValueDeclaration.Parent - isLocalThisPropertyAssignment := isAssignmentDeclaration && symbol.Parent.ValueDeclaration == ctor.Parent + isLocalPropertyDeclaration := ctor.Parent() == symbol.ValueDeclaration.Parent() + isLocalParameterProperty := ctor == symbol.ValueDeclaration.Parent() + isLocalThisPropertyAssignment := isAssignmentDeclaration && symbol.Parent.ValueDeclaration == ctor.Parent() isLocalThisPropertyAssignmentConstructorFunction := isAssignmentDeclaration && symbol.Parent.ValueDeclaration == ctor isWriteableSymbol := isLocalPropertyDeclaration || isLocalParameterProperty || isLocalThisPropertyAssignment || isLocalThisPropertyAssignmentConstructorFunction return !isWriteableSymbol @@ -28316,7 +28316,7 @@ func hasRestParameter(signature *ast.Node) bool { } func isRestParameter(param *ast.Node) bool { - return param.AsParameterDeclaration().DotDotDotToken != nil + return param.AsParameterDeclaration().DotDotDotToken() != nil } func getNameFromIndexInfo(info *IndexInfo) string { @@ -28749,10 +28749,10 @@ func (c *Checker) markLinkedReferences(location *ast.Node, hint ReferenceHint, p // destructuring assignment target. When it appears in an ordinary object literal expression, the checker // checks the initializer and never resolves the property name, so resolving it here would report a spurious // "No value exists in scope for the shorthand property" diagnostic. Skip such names to match checking. - if parent := location.Parent; ast.IsShorthandPropertyAssignment(parent) && + if parent := location.Parent(); ast.IsShorthandPropertyAssignment(parent) && parent.Name() == location && - parent.AsShorthandPropertyAssignment().ObjectAssignmentInitializer != nil && - !ast.IsAssignmentTarget(parent.Parent) { + parent.AsShorthandPropertyAssignment().ObjectAssignmentInitializer() != nil && + !ast.IsAssignmentTarget(parent.Parent()) { return } res := ast.FindManyAncestors(location, ast.IsMetaProperty, ast.IsDecorator, ast.IsForInOrOfStatement, ast.IsComputedPropertyName, ast.IsHeritageClause) @@ -28769,8 +28769,8 @@ func (c *Checker) markLinkedReferences(location *ast.Node, hint ReferenceHint, p // `this` parameters) are never resolved during normal checking, so resolving them here would // report spurious diagnostics. Only bail out for such invalid-position decorators; valid // decorator expressions must still be resolved and marked for emit. - decorated := decorator.Parent - if decorated != nil && !ast.NodeCanBeDecorated(c.legacyDecorators, decorated, decorated.Parent, decorated.Parent.Parent) { + decorated := decorator.Parent() + if decorated != nil && !ast.NodeCanBeDecorated(c.legacyDecorators, decorated, decorated.Parent(), decorated.Parent().Parent()) { return } } @@ -28780,10 +28780,10 @@ func (c *Checker) markLinkedReferences(location *ast.Node, hint ReferenceHint, p // Resolving identifiers in the RHS here would report spurious diagnostics. if forNode != nil { data := forNode.AsForInOrOfStatement() - if ast.IsVariableDeclarationList(data.Initializer) && - len(data.Initializer.AsVariableDeclarationList().Declarations.Nodes) == 0 && - data.Expression != nil && - (location == data.Expression || ast.IsNodeDescendantOf(location, data.Expression)) { + if ast.IsVariableDeclarationList(data.Initializer()) && + len(data.Initializer().AsVariableDeclarationList().Declarations().Nodes) == 0 && + data.Expression() != nil && + (location == data.Expression() || ast.IsNodeDescendantOf(location, data.Expression())) { return } } @@ -28791,7 +28791,7 @@ func (c *Checker) markLinkedReferences(location *ast.Node, hint ReferenceHint, p // (checkEnumMember only checks the member initializer, not the name), so resolving // identifiers in them here would report a spurious "Cannot find name" diagnostic. if computedName != nil { - if ast.IsEnumMember(computedName.Parent) { + if ast.IsEnumMember(computedName.Parent()) { return } if isInvalidComputedPropertyName(computedName) { @@ -28800,15 +28800,15 @@ func (c *Checker) markLinkedReferences(location *ast.Node, hint ReferenceHint, p } if heritageClause != nil { // extends heritage clauses on interfaces are not expressions and are unchecked if they are - if ast.IsInterfaceDeclaration(heritageClause.Parent) { + if ast.IsInterfaceDeclaration(heritageClause.Parent()) { return } // On a class, only the first `extends` type is resolved as a value (the base class); any // additional `extends` types are grammar errors (e.g. `class C extends A extends B` or // `class C extends A, B`) and are never resolved during checking. - if ast.IsClassLike(heritageClause.Parent) && + if ast.IsClassLike(heritageClause.Parent()) && heritageClause.AsHeritageClause().Token == ast.KindExtendsKeyword { - if firstExtends := ast.GetClassExtendsHeritageElement(heritageClause.Parent); firstExtends != nil && + if firstExtends := ast.GetClassExtendsHeritageElement(heritageClause.Parent()); firstExtends != nil && location != firstExtends && !ast.IsNodeDescendantOf(location, firstExtends) { return } @@ -28818,14 +28818,14 @@ func (c *Checker) markLinkedReferences(location *ast.Node, hint ReferenceHint, p // Some non-expression identifiers are also treated as expression identifiers for this purpose, eg, `a` in `b = {a}` or `q` in `import r = q` // This is the exception, rather than the rule - most non-expression identifiers are declaration names. if (ast.IsExpressionNode(location) || - ast.IsShorthandPropertyAssignment(location.Parent)) && + ast.IsShorthandPropertyAssignment(location.Parent())) && shouldMarkIdentifierAliasReferenced(location) { - if ast.IsPropertyAccessOrQualifiedName(location.Parent) { + if ast.IsPropertyAccessOrQualifiedName(location.Parent()) { var left *ast.Node - if ast.IsPropertyAccessExpression(location.Parent) { - left = location.Parent.Expression() + if ast.IsPropertyAccessExpression(location.Parent()) { + left = location.Parent().Expression() } else { - left = location.Parent.AsQualifiedName().Left + left = location.Parent().AsQualifiedName().Left() } if left != location { return // Only mark the LHS (the RHS is a property lookup) @@ -28842,7 +28842,7 @@ func (c *Checker) markLinkedReferences(location *ast.Node, hint ReferenceHint, p if ast.IsPartOfTypeNode(topProp) || isImportTypeQualifierPart(topProp) != nil { return } - topProp = topProp.Parent + topProp = topProp.Parent() } c.markPropertyAliasReferenced(location, nil /*propSymbol*/, nil /*parentType*/) return @@ -28869,7 +28869,7 @@ func (c *Checker) markLinkedReferences(location *ast.Node, hint ReferenceHint, p if !c.compilerOptions.EmitDecoratorMetadata.IsTrue() { return } - if !ast.CanHaveDecorators(location) || !ast.HasDecorators(location) || location.Modifiers() == nil || !ast.NodeCanBeDecorated(c.legacyDecorators, location, location.Parent, location.Parent.Parent) { + if !ast.CanHaveDecorators(location) || !ast.HasDecorators(location) || location.Modifiers() == nil || !ast.NodeCanBeDecorated(c.legacyDecorators, location, location.Parent(), location.Parent().Parent()) { return } @@ -28882,7 +28882,7 @@ func (c *Checker) markLinkedReferences(location *ast.Node, hint ReferenceHint, p func isExportOrExportExpression(location *ast.Node) bool { return ast.FindAncestor(location, func(n *ast.Node) bool { - parent := n.Parent + parent := n.Parent() if parent != nil { if ast.IsAnyExportAssignment(parent) { return parent.Expression() == n && ast.IsEntityNameExpression(n) @@ -28896,7 +28896,7 @@ func isExportOrExportExpression(location *ast.Node) bool { } func shouldMarkIdentifierAliasReferenced(node *ast.IdentifierNode) bool { - parent := node.Parent + parent := node.Parent() if parent != nil { // A property access expression LHS? checkPropertyAccessExpression will handle that. if ast.IsPropertyAccessExpression(parent) && parent.Expression() == node { @@ -28906,8 +28906,8 @@ func shouldMarkIdentifierAliasReferenced(node *ast.IdentifierNode) bool { if ast.IsExportSpecifier(parent) && parent.IsTypeOnly() { return false } - if parent.Parent != nil { - greatGrandparent := parent.Parent.Parent + if parent.Parent() != nil { + greatGrandparent := parent.Parent().Parent() if greatGrandparent != nil && ast.IsExportDeclaration(greatGrandparent) && greatGrandparent.IsTypeOnly() { return false } @@ -28918,7 +28918,7 @@ func shouldMarkIdentifierAliasReferenced(node *ast.IdentifierNode) bool { func isInternalModuleImportEqualsDeclaration(node *ast.Node) bool { return node.Kind == ast.KindImportEqualsDeclaration && - node.AsImportEqualsDeclaration().ModuleReference.Kind != ast.KindExternalModuleReference + node.AsImportEqualsDeclaration().ModuleReference().Kind != ast.KindExternalModuleReference } func (c *Checker) markIdentifierAliasReferenced(location *ast.IdentifierNode) { @@ -28939,7 +28939,7 @@ func (c *Checker) markPropertyAliasReferenced(location *ast.Node /*PropertyAcces if ast.IsPropertyAccessExpression(location) { left = location.Expression() } else { - left = location.AsQualifiedName().Left + left = location.AsQualifiedName().Left() } if ast.IsThisIdentifier(left) || !ast.IsIdentifier(left) { return @@ -28977,7 +28977,7 @@ func (c *Checker) markPropertyAliasReferenced(location *ast.Node /*PropertyAcces if ast.IsPropertyAccessExpression(location) { right = location.AsPropertyAccessExpression().Name() } else { - right = location.AsQualifiedName().Right + right = location.AsQualifiedName().Right() } var lexicallyScopedSymbol *ast.Symbol if ast.IsPrivateIdentifier(right) { @@ -28998,7 +28998,7 @@ func (c *Checker) markPropertyAliasReferenced(location *ast.Node /*PropertyAcces prop = c.getPropertyOfType(apparentType, right.Text()) } } - if !(prop != nil && (isConstEnumOrConstEnumOnlyModule(prop) || prop.Flags&ast.SymbolFlagsEnumMember != 0 && location.Parent.Kind == ast.KindEnumMember)) { + if !(prop != nil && (isConstEnumOrConstEnumOnlyModule(prop) || prop.Flags&ast.SymbolFlagsEnumMember != 0 && location.Parent().Kind == ast.KindEnumMember)) { c.markAliasReferenced(parentSymbol, location) } } @@ -29008,8 +29008,8 @@ func isPartOfImportEqualsModuleReference(location *ast.Node) bool { if importEquals == nil { return false } - for node := location; node != nil && node != importEquals; node = node.Parent { - if node == importEquals.AsImportEqualsDeclaration().ModuleReference { + for node := location; node != nil && node != importEquals; node = node.Parent() { + if node == importEquals.AsImportEqualsDeclaration().ModuleReference() { return true } } @@ -29079,7 +29079,7 @@ func (c *Checker) markImportEqualsAliasReferenced(location *ast.Node /*ImportEqu } func (c *Checker) markExportSpecifierAliasReferenced(location *ast.ExportSpecifierNode) { - if location.Parent.Parent.ModuleSpecifier() == nil && !location.IsTypeOnly() && !location.Parent.Parent.IsTypeOnly() { + 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" } @@ -29250,7 +29250,7 @@ func (c *Checker) markDecoratorAliasReferenced(node *ast.Node /*HasDecorators*/) c.markDecoratorMedataDataTypeNodeAsReferenced(node.Type()) case ast.KindParameter: c.markDecoratorMedataDataTypeNodeAsReferenced(c.getParameterTypeNodeForDecoratorCheck(node)) - containingSignature := node.Parent + containingSignature := node.Parent() for _, p := range containingSignature.Parameters() { c.markDecoratorMedataDataTypeNodeAsReferenced(c.getParameterTypeNodeForDecoratorCheck(p)) } @@ -29260,7 +29260,7 @@ func (c *Checker) markDecoratorAliasReferenced(node *ast.Node /*HasDecorators*/) func (c *Checker) getParameterTypeNodeForDecoratorCheck(node *ast.ParameterDeclarationNode) *ast.Node { typeNode := node.Type() - if node.AsParameterDeclaration().DotDotDotToken != nil { + if node.AsParameterDeclaration().DotDotDotToken() != nil { return ast.GetRestParameterElementType(typeNode) } return typeNode @@ -29279,17 +29279,17 @@ func (c *Checker) getEntityNameForDecoratorMetadata(node *ast.Node) *ast.Node { } switch node.Kind { case ast.KindIntersectionType: - return c.getEntityNameForDecoratorMetadataFromTypeList(node.AsIntersectionTypeNode().Types.Nodes) + return c.getEntityNameForDecoratorMetadataFromTypeList(node.AsIntersectionTypeNode().Types().Nodes) case ast.KindUnionType: - return c.getEntityNameForDecoratorMetadataFromTypeList(node.AsUnionTypeNode().Types.Nodes) + return c.getEntityNameForDecoratorMetadataFromTypeList(node.AsUnionTypeNode().Types().Nodes) case ast.KindConditionalType: - return c.getEntityNameForDecoratorMetadataFromTypeList([]*ast.Node{node.AsConditionalTypeNode().TrueType, node.AsConditionalTypeNode().FalseType}) + return c.getEntityNameForDecoratorMetadataFromTypeList([]*ast.Node{node.AsConditionalTypeNode().TrueType(), node.AsConditionalTypeNode().FalseType()}) case ast.KindParenthesizedType: - return c.getEntityNameForDecoratorMetadata(node.AsParenthesizedTypeNode().Type) + return c.getEntityNameForDecoratorMetadata(node.AsParenthesizedTypeNode().Type()) case ast.KindNamedTupleMember: - return c.getEntityNameForDecoratorMetadata(node.AsNamedTupleMember().Type) + return c.getEntityNameForDecoratorMetadata(node.AsNamedTupleMember().Type()) case ast.KindTypeReference: - return node.AsTypeReferenceNode().TypeName + return node.AsTypeReferenceNode().TypeName() } return nil } @@ -29300,7 +29300,7 @@ func (c *Checker) getEntityNameForDecoratorMetadataFromTypeList(typeNodes []*ast if typeNode.Kind == ast.KindNeverKeyword { continue // Always elide `never` from the union/intersection if possible } - if !c.strictNullChecks && (typeNode.Kind == ast.KindLiteralType && typeNode.AsLiteralTypeNode().Literal.Kind == ast.KindNullKeyword || typeNode.Kind == ast.KindUndefinedKeyword) { + if !c.strictNullChecks && (typeNode.Kind == ast.KindLiteralType && typeNode.AsLiteralTypeNode().Literal().Kind == ast.KindNullKeyword || typeNode.Kind == ast.KindUndefinedKeyword) { continue // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } individualEntityName := c.getEntityNameForDecoratorMetadata(typeNode) @@ -29359,10 +29359,10 @@ func (c *Checker) markAliasSymbolAsReferenced(symbol *ast.Symbol) { // We defer checking of the reference of an `import =` until the import itself is referenced, // This way a chain of imports can be elided if ultimately the final input is only used in a type // position. - if ast.IsImportEqualsDeclaration(node) && node.AsImportEqualsDeclaration().ModuleReference.Kind != ast.KindExternalModuleReference { + if ast.IsImportEqualsDeclaration(node) && node.AsImportEqualsDeclaration().ModuleReference().Kind != ast.KindExternalModuleReference { if c.getSymbolFlags(c.resolveSymbol(symbol))&ast.SymbolFlagsValue != 0 { // import foo = - left := ast.GetFirstIdentifier(node.AsImportEqualsDeclaration().ModuleReference) + left := ast.GetFirstIdentifier(node.AsImportEqualsDeclaration().ModuleReference()) c.markIdentifierAliasReferenced(left) } } @@ -29419,7 +29419,7 @@ func (c *Checker) markEntityNameOrEntityExpressionAsReference(typeName *ast.Node func getEntityNameFromTypeNode(node *ast.TypeNode) *ast.Node { switch node.Kind { case ast.KindTypeReference: - return node.AsTypeReferenceNode().TypeName + return node.AsTypeReferenceNode().TypeName() case ast.KindExpressionWithTypeArguments: if ast.IsEntityNameExpression(node.Expression()) { @@ -29539,11 +29539,11 @@ func (c *Checker) getTypeOfFirstParameterOfSignatureWithFallback(signature *Sign func getMappedTypeModifiers(t *Type) MappedTypeModifiers { declaration := t.AsMappedType().declaration var modifiers MappedTypeModifiers - if declaration.ReadonlyToken != nil { - modifiers |= core.IfElse(declaration.ReadonlyToken.Kind == ast.KindMinusToken, MappedTypeModifiersExcludeReadonly, MappedTypeModifiersIncludeReadonly) + if declaration.ReadonlyToken() != nil { + modifiers |= core.IfElse(declaration.ReadonlyToken().Kind == ast.KindMinusToken, MappedTypeModifiersExcludeReadonly, MappedTypeModifiersIncludeReadonly) } - if declaration.QuestionToken != nil { - modifiers |= core.IfElse(declaration.QuestionToken.Kind == ast.KindMinusToken, MappedTypeModifiersExcludeOptional, MappedTypeModifiersIncludeOptional) + if declaration.QuestionToken() != nil { + modifiers |= core.IfElse(declaration.QuestionToken().Kind == ast.KindMinusToken, MappedTypeModifiersExcludeOptional, MappedTypeModifiersIncludeOptional) } return modifiers } @@ -29660,7 +29660,7 @@ func (c *Checker) getConstraintDeclaration(t *Type) *ast.Node { if t.symbol != nil { for _, d := range t.symbol.Declarations { if ast.IsTypeParameterDeclaration(d) { - if constraint := d.AsTypeParameterDeclaration().Constraint; constraint != nil { + if constraint := d.AsTypeParameterDeclaration().Constraint(); constraint != nil { return constraint } } @@ -29897,7 +29897,7 @@ func (c *Checker) getContextualType(node *ast.Node, contextFlags ContextFlags) * if index >= 0 { return c.contextualInfos[index].t } - parent := node.Parent + parent := node.Parent() switch parent.Kind { case ast.KindVariableDeclaration, ast.KindParameter, ast.KindPropertyDeclaration, ast.KindPropertySignature, ast.KindBindingElement: return c.getContextualTypeForInitializerExpression(node, contextFlags) @@ -29922,7 +29922,7 @@ func (c *Checker) getContextualType(node *ast.Node, contextFlags ContextFlags) * ast.KindShorthandPropertyAssignment: return c.getContextualTypeForObjectLiteralElement(parent, contextFlags) case ast.KindSpreadAssignment: - return c.getContextualType(parent.Parent, contextFlags) + return c.getContextualType(parent.Parent(), contextFlags) case ast.KindArrayLiteralExpression: t := c.getApparentTypeOfContextualType(parent, contextFlags) elementIndex := ast.IndexOfNode(parent.Elements(), node) @@ -29934,7 +29934,7 @@ func (c *Checker) getContextualType(node *ast.Node, contextFlags ContextFlags) * case ast.KindConditionalExpression: return c.getContextualTypeForConditionalOperand(node, contextFlags) case ast.KindTemplateSpan: - return c.getContextualTypeForSubstitutionExpression(parent.Parent, node) + return c.getContextualTypeForSubstitutionExpression(parent.Parent(), node) case ast.KindParenthesizedExpression: return c.getContextualType(parent, contextFlags) case ast.KindNonNullExpression: @@ -29967,7 +29967,7 @@ func (c *Checker) getContextualType(node *ast.Node, contextFlags ContextFlags) * // Otherwise, in a binding pattern inside a variable or parameter declaration, // the contextual type of an initializer expression is the type annotation of the containing declaration, if present. func (c *Checker) getContextualTypeForInitializerExpression(node *ast.Node, contextFlags ContextFlags) *Type { - declaration := node.Parent + declaration := node.Parent() initializer := declaration.Initializer() if node == initializer { result := c.getContextualTypeForVariableLikeDeclaration(declaration, contextFlags) @@ -30002,7 +30002,7 @@ func (c *Checker) getContextualTypeForVariableLikeDeclaration(declaration *ast.N // Return contextual type of parameter or undefined if no contextual type is available func (c *Checker) getContextuallyTypedParameterType(parameter *ast.Node) *Type { - fn := parameter.Parent + fn := parameter.Parent() if !c.isContextSensitiveFunctionOrObjectLiteralMethod(fn) { return nil } @@ -30105,8 +30105,8 @@ func (c *Checker) getSpreadArgumentType(args []*ast.Node, index int, argCount in } info.flags = ElementFlagsRequired } - if ast.IsSyntheticExpression(arg) && arg.AsSyntheticExpression().TupleNameSource != nil { - info.labeledDeclaration = arg.AsSyntheticExpression().TupleNameSource + if ast.IsSyntheticExpression(arg) && arg.AsSyntheticExpression().TupleNameSource() != nil { + info.labeledDeclaration = arg.AsSyntheticExpression().TupleNameSource() } types = append(types, t) infos = append(infos, info) @@ -30131,7 +30131,7 @@ func (c *Checker) getContextualTypeForBindingElement(declaration *ast.Node, cont if ast.IsBindingPattern(name) || ast.IsComputedNonLiteralName(name) { return nil } - parent := declaration.Parent.Parent + parent := declaration.Parent().Parent() parentType := c.getContextualTypeForVariableLikeDeclaration(parent, contextFlags) if parentType == nil { if !ast.IsBindingElement(parent) && parent.Initializer() != nil { @@ -30142,7 +30142,7 @@ func (c *Checker) getContextualTypeForBindingElement(declaration *ast.Node, cont return nil } if ast.IsArrayBindingPattern(parent.Name()) { - index := slices.Index(declaration.Parent.Elements(), declaration) + index := slices.Index(declaration.Parent().Elements(), declaration) if index < 0 { return nil } @@ -30156,9 +30156,9 @@ func (c *Checker) getContextualTypeForBindingElement(declaration *ast.Node, cont } func (c *Checker) getContextualTypeForStaticPropertyDeclaration(declaration *ast.Node, contextFlags ContextFlags) *Type { - if ast.IsExpression(declaration.Parent) { + if ast.IsExpression(declaration.Parent()) { // Don't contextually type a static property by its own class, its type might still be in-progress and that would cause spurious circularities - if parentType := c.getContextualType(declaration.Parent, contextFlags); parentType != nil && parentType.symbol != c.getSymbolOfDeclaration(declaration.Parent) { + if parentType := c.getContextualType(declaration.Parent(), contextFlags); parentType != nil && parentType.symbol != c.getSymbolOfDeclaration(declaration.Parent()) { return c.getTypeOfPropertyOfContextualType(parentType, c.getSymbolOfDeclaration(declaration).Name) } } @@ -30270,7 +30270,7 @@ func (c *Checker) getContextualTypeForYieldOperand(node *ast.Node, contextFlags contextualReturnType := c.getContextualReturnType(fn, contextFlags) if contextualReturnType != nil { isAsyncGenerator := functionFlags&ast.FunctionFlagsAsync != 0 - isYieldStar := node.AsYieldExpression().AsteriskToken != nil + isYieldStar := node.AsYieldExpression().AsteriskToken() != nil if !isYieldStar && contextualReturnType.flags&TypeFlagsUnion != 0 { contextualReturnType = c.filterType(contextualReturnType, func(t *Type) bool { return c.getIterationTypeOfGeneratorFunctionReturnType(IterationTypeKindReturn, t, isAsyncGenerator) != nil @@ -30354,16 +30354,16 @@ func (c *Checker) getContextualTypeForDecorator(decorator *ast.Node) *Type { } func (c *Checker) getContextualTypeForBinaryOperand(node *ast.Node, contextFlags ContextFlags) *Type { - binary := node.Parent.AsBinaryExpression() - if t := binary.Type; t != nil { + binary := node.Parent().AsBinaryExpression() + if t := binary.Type(); t != nil { return c.getTypeFromTypeNode(t) } - switch binary.OperatorToken.Kind { + switch binary.OperatorToken().Kind { case ast.KindEqualsToken, ast.KindAmpersandAmpersandEqualsToken, ast.KindBarBarEqualsToken, ast.KindQuestionQuestionEqualsToken: // In an assignment expression, the right operand is contextually typed by the type of the left operand // unless it's an assignment declaration. - if node == binary.Right { - target := ast.GetLeftmostExpression(binary.Left, false) + if node == binary.Right() { + target := ast.GetLeftmostExpression(binary.Left(), false) if !(ast.IsIdentifier(target) && c.getResolvedSymbol(target).Flags&ast.SymbolFlagsModuleExports != 0) { return c.getContextualTypeForAssignmentExpression(binary) } @@ -30375,12 +30375,12 @@ func (c *Checker) getContextualTypeForBinaryOperand(node *ast.Node, contextFlags // by the type of the left operand, except for the special case of Javascript declarations of the form // `namespace.prop = namespace.prop || {}`. t := c.getContextualType(binary.AsNode(), contextFlags) - if node == binary.Right && (t == nil || c.patternForType[t] != nil) { - return c.getTypeOfExpression(binary.Left) + if node == binary.Right() && (t == nil || c.patternForType[t] != nil) { + return c.getTypeOfExpression(binary.Left()) } return t case ast.KindAmpersandAmpersandToken, ast.KindCommaToken: - if node == binary.Right { + if node == binary.Right() { return c.getContextualType(binary.AsNode(), contextFlags) } } @@ -30388,7 +30388,7 @@ func (c *Checker) getContextualTypeForBinaryOperand(node *ast.Node, contextFlags } func (c *Checker) getContextualTypeForAssignmentExpression(binary *ast.BinaryExpression) *Type { - left := binary.Left + left := binary.Left() if ast.IsAccessExpression(left) { expr := left.Expression() switch expr.Kind { @@ -30408,7 +30408,7 @@ func (c *Checker) getContextualTypeForAssignmentExpression(binary *ast.BinaryExp if ast.IsPropertyAccessExpression(left) { return c.getTypeOfPropertyOfContextualType(c.getTypeFromTypeNode(typeNode), left.Name().Text()) } - nameType := c.checkExpressionCached(left.AsElementAccessExpression().ArgumentExpression) + nameType := c.checkExpressionCached(left.AsElementAccessExpression().ArgumentExpression()) if isTypeUsableAsPropertyName(nameType) { return c.getTypeOfPropertyOfContextualTypeEx(c.getTypeFromTypeNode(typeNode), getPropertyNameFromType(nameType), nameType) } @@ -30434,7 +30434,7 @@ func (c *Checker) getContextualTypeForAssignmentExpression(binary *ast.BinaryExp symbol = c.getPropertyOfType(thisType, name.Text()) } } else { - propType := c.checkExpressionCached(left.AsElementAccessExpression().ArgumentExpression) + propType := c.checkExpressionCached(left.AsElementAccessExpression().ArgumentExpression()) if isTypeUsableAsPropertyName(propType) { symbol = c.getPropertyOfType(thisType, getPropertyNameFromType(propType)) } @@ -30468,7 +30468,7 @@ func (c *Checker) getContextualTypeForObjectLiteralElement(element *ast.Node, co if t := element.Type(); t != nil && !ast.IsObjectLiteralMethod(element) { return c.getTypeFromTypeNode(t) } - objectLiteral := element.Parent + objectLiteral := element.Parent() t := c.getApparentTypeOfContextualType(objectLiteral, contextFlags) if t != nil { if c.hasBindableName(element) { @@ -30567,16 +30567,16 @@ func (c *Checker) getContextualTypeForElementExpression(t *Type, index int, leng // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. func (c *Checker) getContextualTypeForConditionalOperand(node *ast.Node, contextFlags ContextFlags) *Type { - conditional := node.Parent.AsConditionalExpression() - if node == conditional.WhenTrue || node == conditional.WhenFalse { - return c.getContextualType(node.Parent, contextFlags) + conditional := node.Parent().AsConditionalExpression() + if node == conditional.WhenTrue() || node == conditional.WhenFalse() { + return c.getContextualType(node.Parent(), contextFlags) } return nil } func (c *Checker) getContextualTypeForSubstitutionExpression(template *ast.Node, substitutionExpression *ast.Node) *Type { - if ast.IsTaggedTemplateExpression(template.Parent) { - return c.getContextualTypeForArgument(template.Parent, substitutionExpression) + if ast.IsTaggedTemplateExpression(template.Parent()) { + return c.getContextualTypeForArgument(template.Parent(), substitutionExpression) } return nil } @@ -30592,12 +30592,12 @@ func (c *Checker) getEffectiveCallArguments(node *ast.Node) []*ast.Node { // This attributes Type does not include a children property yet, the same way a fragment created with does not at this stage return []*ast.Node{c.createSyntheticExpression(node, c.emptyFreshJsxObjectType, false, nil)} case ast.IsTaggedTemplateExpression(node): - template := node.AsTaggedTemplateExpression().Template + template := node.AsTaggedTemplateExpression().Template() firstArg := c.createSyntheticExpression(template, c.getGlobalTemplateStringsArrayType(), false, nil) if !ast.IsTemplateExpression(template) { return []*ast.Node{firstArg} } - spans := template.AsTemplateExpression().TemplateSpans.Nodes + spans := template.AsTemplateExpression().TemplateSpans().Nodes args := make([]*ast.Node, len(spans)+1) args[0] = firstArg for i, span := range spans { @@ -30608,9 +30608,9 @@ func (c *Checker) getEffectiveCallArguments(node *ast.Node) []*ast.Node { return c.getEffectiveDecoratorArguments(node) case ast.IsBinaryExpression(node): // Handles instanceof operator - return []*ast.Node{node.AsBinaryExpression().Left} + return []*ast.Node{node.AsBinaryExpression().Left()} case ast.IsJsxOpeningLikeElement(node): - if len(node.Attributes().Properties()) != 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 @@ -30663,7 +30663,7 @@ func isSpreadArgument(arg *ast.Node) bool { func (c *Checker) createSyntheticExpression(parent *ast.Node, t *Type, isSpread bool, tupleNameSource *ast.Node) *ast.Node { result := c.factory.NewSyntheticExpression(t, isSpread, tupleNameSource) result.Loc = parent.Loc - result.Parent = parent + result.SetParent(parent) return result } @@ -30707,7 +30707,7 @@ func (c *Checker) getDecoratorCallSignature(decorator *ast.Node) *Signature { } func (c *Checker) getLegacyDecoratorCallSignature(decorator *ast.Node) *Signature { - node := decorator.Parent + node := decorator.Parent() links := c.signatureLinks.Get(node) if links.decoratorSignature == nil { links.decoratorSignature = c.anySignature @@ -30719,24 +30719,24 @@ func (c *Checker) getLegacyDecoratorCallSignature(decorator *ast.Node) *Signatur targetParam := c.newParameter("target", targetType) links.decoratorSignature = c.newCallSignature(nil, nil, []*ast.Symbol{targetParam}, c.getUnionType([]*Type{targetType, c.voidType})) case ast.KindParameter: - if !ast.IsConstructorDeclaration(node.Parent) && !(ast.IsMethodDeclaration(node.Parent) || ast.IsSetAccessorDeclaration(node.Parent) && ast.IsClassLike(node.Parent.Parent)) { + if !ast.IsConstructorDeclaration(node.Parent()) && !(ast.IsMethodDeclaration(node.Parent()) || ast.IsSetAccessorDeclaration(node.Parent()) && ast.IsClassLike(node.Parent().Parent())) { break } - if ast.GetThisParameter(node.Parent) == node { + if ast.GetThisParameter(node.Parent()) == node { break } - index := slices.Index(node.Parent.Parameters(), node) - core.IfElse(ast.GetThisParameter(node.Parent) != nil, 1, 0) + index := slices.Index(node.Parent().Parameters(), node) - core.IfElse(ast.GetThisParameter(node.Parent()) != nil, 1, 0) debug.Assert(index >= 0) // A parameter declaration decorator will have three arguments (see `ParameterDecorator` in // core.d.ts). var targetType *Type var keyType *Type - if ast.IsConstructorDeclaration(node.Parent) { - targetType = c.getTypeOfSymbol(c.getSymbolOfDeclaration(node.Parent.Parent)) + if ast.IsConstructorDeclaration(node.Parent()) { + targetType = c.getTypeOfSymbol(c.getSymbolOfDeclaration(node.Parent().Parent())) keyType = c.undefinedType } else { - targetType = c.getParentTypeOfClassElement(node.Parent) - keyType = c.getClassElementPropertyKeyType(node.Parent) + targetType = c.getParentTypeOfClassElement(node.Parent()) + keyType = c.getClassElementPropertyKeyType(node.Parent()) } indexType := c.getNumberLiteralType(jsnum.Number(index)) targetParam := c.newParameter("target", targetType) @@ -30744,7 +30744,7 @@ func (c *Checker) getLegacyDecoratorCallSignature(decorator *ast.Node) *Signatur indexParam := c.newParameter("parameterIndex", indexType) links.decoratorSignature = c.newCallSignature(nil, nil, []*ast.Symbol{targetParam, keyParam, indexParam}, c.voidType) case ast.KindMethodDeclaration, ast.KindGetAccessor, ast.KindSetAccessor, ast.KindPropertyDeclaration: - if !ast.IsClassLike(node.Parent) { + if !ast.IsClassLike(node.Parent()) { break } // A method or accessor declaration decorator will have either two or three arguments (see @@ -30854,7 +30854,7 @@ func (c *Checker) getESDecoratorCallSignature(decorator *ast.Node) *Signature { // initializers. In most cases, the "target" argument corresponds to the "input type" in some way, and the // return value similarly corresponds to the "output type" (though if the "output type" is `void` or // `undefined` then the "output type" is the "input type"). - node := decorator.Parent + node := decorator.Parent() links := c.signatureLinks.Get(node) if links.decoratorSignature == nil { links.decoratorSignature = c.anySignature @@ -30866,7 +30866,7 @@ func (c *Checker) getESDecoratorCallSignature(decorator *ast.Node) *Signature { contextType := c.newClassDecoratorContextType(targetType) links.decoratorSignature = c.newESDecoratorCallSignature(targetType, contextType, targetType) case ast.KindMethodDeclaration, ast.KindGetAccessor, ast.KindSetAccessor: - if !ast.IsClassLike(node.Parent) { + if !ast.IsClassLike(node.Parent()) { break } // Method decorators have a `context` of `ClassMethodDecoratorContext`, where the @@ -30888,9 +30888,9 @@ func (c *Checker) getESDecoratorCallSignature(decorator *ast.Node) *Signature { } var thisType *Type if ast.HasStaticModifier(node) { - thisType = c.getTypeOfSymbol(c.getSymbolOfDeclaration(node.Parent)) + thisType = c.getTypeOfSymbol(c.getSymbolOfDeclaration(node.Parent())) } else { - thisType = c.getDeclaredTypeOfClassOrInterface(c.getSymbolOfDeclaration(node.Parent)) + thisType = c.getDeclaredTypeOfClassOrInterface(c.getSymbolOfDeclaration(node.Parent())) } // We wrap the "input type", if necessary, to match the decoration target. For getters this is // something like `() => inputType`, for setters it's `(value: inputType) => void` and for @@ -30907,7 +30907,7 @@ func (c *Checker) getESDecoratorCallSignature(decorator *ast.Node) *Signature { contextType := c.newClassMemberDecoratorContextTypeForNode(node, thisType, valueType) links.decoratorSignature = c.newESDecoratorCallSignature(targetType, contextType, targetType) case ast.KindPropertyDeclaration: - if !ast.IsClassLike(node.Parent) { + if !ast.IsClassLike(node.Parent()) { break } // Field decorators have a `context` of `ClassFieldDecoratorContext` and @@ -30918,9 +30918,9 @@ func (c *Checker) getESDecoratorCallSignature(decorator *ast.Node) *Signature { valueType := c.getTypeOfNode(node) var thisType *Type if ast.HasStaticModifier(node) { - thisType = c.getTypeOfSymbol(c.getSymbolOfDeclaration(node.Parent)) + thisType = c.getTypeOfSymbol(c.getSymbolOfDeclaration(node.Parent())) } else { - thisType = c.getDeclaredTypeOfClassOrInterface(c.getSymbolOfDeclaration(node.Parent)) + thisType = c.getDeclaredTypeOfClassOrInterface(c.getSymbolOfDeclaration(node.Parent())) } // The `target` of an auto-accessor decorator is a `{ get, set }` object, representing the // runtime-generated getter and setter that are added to the class/prototype. The `target` of a @@ -31073,7 +31073,7 @@ func (c *Checker) newTypedPropertyDescriptorType(propertyType *Type) *Type { } func (c *Checker) getParentTypeOfClassElement(node *ast.Node) *Type { - classSymbol := c.getSymbolOfNode(node.Parent) + classSymbol := c.getSymbolOfNode(node.Parent()) if ast.IsStatic(node) { return c.getTypeOfSymbol(classSymbol) } @@ -31450,16 +31450,16 @@ func (c *Checker) isContextSensitive(node *ast.Node) bool { case ast.KindArrayLiteralExpression: return core.Some(node.Elements(), c.isContextSensitive) case ast.KindConditionalExpression: - return c.isContextSensitive(node.AsConditionalExpression().WhenTrue) || c.isContextSensitive(node.AsConditionalExpression().WhenFalse) + return c.isContextSensitive(node.AsConditionalExpression().WhenTrue()) || c.isContextSensitive(node.AsConditionalExpression().WhenFalse()) case ast.KindBinaryExpression: binary := node.AsBinaryExpression() - return ast.NodeKindIs(binary.OperatorToken, ast.KindBarBarToken, ast.KindQuestionQuestionToken) && (c.isContextSensitive(binary.Left) || c.isContextSensitive(binary.Right)) + return ast.NodeKindIs(binary.OperatorToken(), ast.KindBarBarToken, ast.KindQuestionQuestionToken) && (c.isContextSensitive(binary.Left()) || c.isContextSensitive(binary.Right())) case ast.KindPropertyAssignment: return c.isContextSensitive(node.Initializer()) case ast.KindParenthesizedExpression: return c.isContextSensitive(node.Expression()) case ast.KindJsxAttributes: - return core.Some(node.Properties(), 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() @@ -32021,7 +32021,7 @@ func (c *Checker) isSomeSymbolAssigned(rootDeclaration *ast.Node) bool { func (c *Checker) isSomeSymbolAssignedWorker(node *ast.Node) bool { if node.Kind == ast.KindIdentifier { - return c.isSymbolAssigned(c.getSymbolOfDeclaration(node.Parent)) + return c.isSymbolAssigned(c.getSymbolOfDeclaration(node.Parent())) } return core.Some(node.Elements(), func(e *ast.Node) bool { return e.Name() != nil && c.isSomeSymbolAssignedWorker(e.Name()) @@ -32054,13 +32054,13 @@ func (c *Checker) getNarrowableTypeForReference(t *Type, reference *ast.Node, ch } func (c *Checker) isConstraintPosition(t *Type, node *ast.Node) bool { - parent := node.Parent + parent := node.Parent() // In an element access obj[x], we consider obj to be in a constraint position, except when obj is of // a generic type without a nullable constraint and x is a generic type. This is because when both obj // and x are of generic types T and K, we want the resulting type to be T[K]. return ast.IsPropertyAccessExpression(parent) || ast.IsQualifiedName(parent) || (ast.IsCallExpression(parent) || ast.IsNewExpression(parent)) && parent.Expression() == node || - ast.IsElementAccessExpression(parent) && parent.Expression() == node && !(someType(t, c.isGenericTypeWithoutNullableConstraint) && c.isGenericIndexType(c.getTypeOfExpression(parent.AsElementAccessExpression().ArgumentExpression))) + ast.IsElementAccessExpression(parent) && parent.Expression() == node && !(someType(t, c.isGenericTypeWithoutNullableConstraint) && c.isGenericIndexType(c.getTypeOfExpression(parent.AsElementAccessExpression().ArgumentExpression()))) } func (c *Checker) isGenericTypeWithUnionConstraint(t *Type) bool { @@ -32083,7 +32083,7 @@ func (c *Checker) hasContextualTypeWithNoGenericTypes(node *ast.Node, checkMode // If check mode has `CheckMode.RestBindingElement`, we skip binding pattern contextual types, // as we want the type of a rest element to be generic when possible. if (ast.IsIdentifier(node) || ast.IsPropertyAccessExpression(node) || ast.IsElementAccessExpression(node)) && - !((ast.IsJsxOpeningElement(node.Parent) || ast.IsJsxSelfClosingElement(node.Parent)) && node.Parent.TagName() == node) { + !((ast.IsJsxOpeningElement(node.Parent()) || ast.IsJsxSelfClosingElement(node.Parent())) && node.Parent().TagName() == node) { contextualType := c.getContextualType(node, core.IfElse(checkMode&CheckModeRestBindingElement != 0, ContextFlagsSkipBindingPatterns, ContextFlagsNone)) if contextualType != nil { return !c.isGenericType(contextualType) @@ -32149,8 +32149,8 @@ func (c *Checker) getSymbolAtLocation(node *ast.Node, ignoreErrors bool) *ast.Sy } return nil } - parent := node.Parent - grandParent := parent.Parent + parent := node.Parent() + grandParent := parent.Parent() if node.Flags&ast.NodeFlagsInWithStatement != 0 { // We cannot answer semantic questions within a with block, do not proceed any further @@ -32228,7 +32228,7 @@ func (c *Checker) getSymbolAtLocation(node *ast.Node, ignoreErrors bool) *ast.Sy // constructor keyword for an overload, should take us to the definition if it exist constructorDeclaration := parent if constructorDeclaration != nil && constructorDeclaration.Kind == ast.KindConstructor { - return constructorDeclaration.Parent.Symbol() + return constructorDeclaration.Parent().Symbol() } return nil case ast.KindStringLiteral, ast.KindNoSubstitutionTemplateLiteral: @@ -32239,7 +32239,7 @@ func (c *Checker) getSymbolAtLocation(node *ast.Node, ignoreErrors bool) *ast.Sy if (ast.IsExternalModuleImportEqualsDeclaration(grandParent) && ast.GetExternalModuleImportEqualsDeclarationExpression(grandParent) == node) || ((parent.Kind == ast.KindImportDeclaration || parent.Kind == ast.KindJSImportDeclaration || parent.Kind == ast.KindExportDeclaration) && ast.GetExternalModuleName(parent) == node) || ast.IsVariableDeclarationInitializedToRequire(grandParent) || ast.IsImportCall(parent) || - (ast.IsLiteralTypeNode(parent) && ast.IsLiteralImportTypeNode(grandParent) && grandParent.AsImportTypeNode().Argument == parent) { + (ast.IsLiteralTypeNode(parent) && ast.IsLiteralImportTypeNode(grandParent) && grandParent.AsImportTypeNode().Argument() == parent) { return c.resolveExternalModuleName(node, node, ignoreErrors, c.getImportAttributesTypeForModuleSpecifier(node)) } if ast.IsCallExpression(parent) && ast.IsBindableObjectDefinePropertyCall(parent) && parent.Arguments()[1] == node { @@ -32250,11 +32250,11 @@ func (c *Checker) getSymbolAtLocation(node *ast.Node, ignoreErrors bool) *ast.Sy // index access var objectType *Type if ast.IsElementAccessExpression(parent) { - if parent.AsElementAccessExpression().ArgumentExpression == node { + if parent.AsElementAccessExpression().ArgumentExpression() == node { objectType = c.getTypeOfExpression(parent.Expression()) } } else if ast.IsLiteralTypeNode(parent) && ast.IsIndexedAccessTypeNode(grandParent) { - objectType = c.getTypeFromTypeNode(grandParent.AsIndexedAccessTypeNode().ObjectType) + objectType = c.getTypeFromTypeNode(grandParent.AsIndexedAccessTypeNode().ObjectType()) } if objectType != nil { @@ -32262,10 +32262,10 @@ func (c *Checker) getSymbolAtLocation(node *ast.Node, ignoreErrors bool) *ast.Sy } return nil case ast.KindDefaultKeyword, ast.KindFunctionKeyword, ast.KindEqualsGreaterThanToken, ast.KindClassKeyword: - return c.getSymbolOfNode(node.Parent) + return c.getSymbolOfNode(node.Parent()) case ast.KindImportType: if ast.IsLiteralImportTypeNode(node) { - return c.getSymbolAtLocation(node.AsImportTypeNode().Argument.AsLiteralTypeNode().Literal, ignoreErrors) + return c.getSymbolAtLocation(node.AsImportTypeNode().Argument().AsLiteralTypeNode().Literal(), ignoreErrors) } return nil case ast.KindExportKeyword: @@ -32277,7 +32277,7 @@ func (c *Checker) getSymbolAtLocation(node *ast.Node, ignoreErrors bool) *ast.Sy } return nil case ast.KindImportKeyword: - if ast.IsImportPhaseMetaProperty(node.Parent) { + if ast.IsImportPhaseMetaProperty(node.Parent()) { return nil } fallthrough @@ -32288,7 +32288,7 @@ func (c *Checker) getSymbolAtLocation(node *ast.Node, ignoreErrors bool) *ast.Sy return nil case ast.KindInstanceOfKeyword: if ast.IsBinaryExpression(parent) { - t := c.getTypeOfExpression(parent.AsBinaryExpression().Right) + t := c.getTypeOfExpression(parent.AsBinaryExpression().Right()) hasInstanceMethodType := c.getSymbolHasInstanceMethodOfObjectType(t) if hasInstanceMethodType != nil && hasInstanceMethodType.symbol != nil { return hasInstanceMethodType.symbol @@ -32300,7 +32300,7 @@ func (c *Checker) getSymbolAtLocation(node *ast.Node, ignoreErrors bool) *ast.Sy return c.checkExpression(node).symbol case ast.KindJsxNamespacedName: if ast.IsJsxTagName(node) && isJsxIntrinsicTagName(node) { - symbol := c.getIntrinsicTagSymbol(node.Parent) + symbol := c.getIntrinsicTagSymbol(node.Parent()) if symbol == c.unknownSymbol { return nil } @@ -32314,9 +32314,9 @@ func (c *Checker) getSymbolAtLocation(node *ast.Node, ignoreErrors bool) *ast.Sy func (c *Checker) getIndexSignaturesAtLocation(node *ast.Node) []*ast.Node { var signatures []*ast.Node - if ast.IsIdentifier(node) && ast.IsPropertyAccessExpression(node.Parent) && node.Parent.Name() == node { + if ast.IsIdentifier(node) && ast.IsPropertyAccessExpression(node.Parent()) && node.Parent().Name() == node { keyType := c.getLiteralTypeFromPropertyName(node) - objectType := c.getTypeOfExpression(node.Parent.Expression()) + objectType := c.getTypeOfExpression(node.Parent().Expression()) for _, t := range objectType.Distributed() { for _, info := range c.getApplicableIndexInfos(t, keyType) { if info.declaration != nil { @@ -32330,9 +32330,9 @@ func (c *Checker) getIndexSignaturesAtLocation(node *ast.Node) []*ast.Node { func (c *Checker) getSymbolOfNameOrPropertyAccessExpression(name *ast.Node) *ast.Symbol { if ast.IsDeclarationName(name) { - return c.getSymbolOfNode(name.Parent) + return c.getSymbolOfNode(name.Parent()) } - if name.Parent.Kind == ast.KindExportAssignment && ast.IsEntityNameExpression(name) { + if name.Parent().Kind == ast.KindExportAssignment && ast.IsEntityNameExpression(name) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression success := c.resolveEntityName( name, @@ -32361,18 +32361,18 @@ func (c *Checker) getSymbolOfNameOrPropertyAccessExpression(name *ast.Node) *ast } for ast.IsRightSideOfQualifiedNameOrPropertyAccess(name) { - name = name.Parent + name = name.Parent() } if isInNameOfExpressionWithTypeArgumentsOrHeritageTypeReference(name) { var meaning ast.SymbolFlags - if name.Parent.Kind == ast.KindExpressionWithTypeArguments || name.Parent.Kind == ast.KindTypeReference { + if name.Parent().Kind == ast.KindExpressionWithTypeArguments || name.Parent().Kind == ast.KindTypeReference { // A heritage element name may appear in type space, value space, or both; // ensure the meaning matches its context. meaning = core.IfElse(ast.IsPartOfTypeNode(name), ast.SymbolFlagsType, ast.SymbolFlagsValue) // In a class 'extends' clause we are also looking for a value. - if ast.IsExpressionWithTypeArgumentsInClassExtendsClause(name.Parent) { + if ast.IsExpressionWithTypeArgumentsInClassExtendsClause(name.Parent()) { meaning = meaning | ast.SymbolFlagsValue } } else { @@ -32397,7 +32397,7 @@ func (c *Checker) getSymbolOfNameOrPropertyAccessExpression(name *ast.Node) *ast isJSDoc := ast.IsJSDocNameReferenceContext(name) if ast.IsIdentifier(name) { if ast.IsJsxTagName(name) && isJsxIntrinsicTagName(name) { - symbol := c.getIntrinsicTagSymbol(name.Parent) + symbol := c.getIntrinsicTagSymbol(name.Parent()) return core.IfElse(symbol == c.unknownSymbol, nil, symbol) } meaning := core.IfElse(isJSDoc, ast.SymbolFlagsValue|ast.SymbolFlagsType|ast.SymbolFlagsNamespace, ast.SymbolFlagsValue) @@ -32440,7 +32440,7 @@ func (c *Checker) getSymbolOfNameOrPropertyAccessExpression(name *ast.Node) *ast return links.resolvedSymbol } } else if ast.IsEntityName(name) && isTypeReferenceIdentifier(name) { - meaning := core.IfElse(name.Parent.Kind == ast.KindTypeReference, ast.SymbolFlagsType, ast.SymbolFlagsNamespace) + meaning := core.IfElse(name.Parent().Kind == ast.KindTypeReference, ast.SymbolFlagsType, ast.SymbolFlagsNamespace) symbol := c.resolveEntityName(name, meaning, true /*ignoreErrors*/, true /*dontResolveAlias*/, nil /*location*/) if symbol != nil && symbol != c.unknownSymbol { return symbol @@ -32451,7 +32451,7 @@ func (c *Checker) getSymbolOfNameOrPropertyAccessExpression(name *ast.Node) *ast return c.getUnresolvedSymbolForEntityName(name) } - if name.Parent.Kind == ast.KindTypePredicate { + if name.Parent().Kind == ast.KindTypePredicate { return c.resolveEntityName( name, ast.SymbolFlagsFunctionScopedVariable, /*meaning*/ @@ -32561,7 +32561,7 @@ func (c *Checker) getTypeOfNode(node *ast.Node) *Type { } if ast.IsBindingPattern(node) { - t := c.getTypeForVariableLikeDeclaration(node.Parent, true /*includeOptionality*/, CheckModeNormal) + t := c.getTypeForVariableLikeDeclaration(node.Parent(), true /*includeOptionality*/, CheckModeNormal) if t != nil { return t } @@ -32579,8 +32579,8 @@ func (c *Checker) getTypeOfNode(node *ast.Node) *Type { } } - if ast.IsMetaProperty(node.Parent) && node.Parent.AsMetaProperty().KeywordToken == node.Kind { - return c.checkMetaPropertyKeyword(node.Parent) + if ast.IsMetaProperty(node.Parent()) && node.Parent().AsMetaProperty().KeywordToken == node.Kind { + return c.checkMetaPropertyKeyword(node.Parent()) } if ast.IsImportAttributes(node) { @@ -32598,10 +32598,10 @@ func (c *Checker) getThisTypeOfObjectLiteralFromContextualType(containingLiteral if thisType != nil { return thisType } - if literal.Parent.Kind != ast.KindPropertyAssignment { + if literal.Parent().Kind != ast.KindPropertyAssignment { break } - literal = literal.Parent.Parent + literal = literal.Parent().Parent() t = c.getApparentTypeOfContextualType(literal, ContextFlagsNone) } return nil @@ -32665,7 +32665,7 @@ func (c *Checker) getApplicableIndexSymbol(t *Type, keyType *Type) *ast.Symbol { func (c *Checker) getRegularTypeOfExpression(expr *ast.Node) *Type { if ast.IsRightSideOfQualifiedNameOrPropertyAccess(expr) { - expr = expr.Parent + expr = expr.Parent() } return c.getRegularTypeOfLiteralType(c.getTypeOfExpression(expr)) } diff --git a/tsc/internal/checker/checker_test.go b/tsc/internal/checker/checker_test.go index 2ed189904d64b..71cfa81779793 100644 --- a/tsc/internal/checker/checker_test.go +++ b/tsc/internal/checker/checker_test.go @@ -49,7 +49,7 @@ foo.bar;` defer done() file := p.GetSourceFile("/foo.ts") interfaceId := file.Statements.Nodes[0].Name() - varId := file.Statements.Nodes[1].AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes[0].Name() + varId := file.Statements.Nodes[1].AsVariableStatement().DeclarationList().AsVariableDeclarationList().Declarations().Nodes[0].Name() propAccess := file.Statements.Nodes[2].Expression() nodes := []*ast.Node{interfaceId, varId, propAccess} for _, node := range nodes { @@ -97,7 +97,7 @@ export type E = D;`, defer done() file := p.GetSourceFile("/main.ts") importClauseAt := func(index int) *ast.Node { - return file.Statements.Nodes[index].AsImportDeclaration().ImportClause + return file.Statements.Nodes[index].AsImportDeclaration().ImportClause() } // An import clause without a default binding has no symbol of its own. A type-only one // should get the same type as the equivalent regular import instead of crashing. @@ -111,7 +111,7 @@ export type E = D;`, } defaultClause := c.GetTypeAtLocation(importClauseAt(3)) - defaultReference := c.GetTypeAtLocation(file.Statements.Nodes[7].AsTypeAliasDeclaration().Type) + defaultReference := c.GetTypeAtLocation(file.Statements.Nodes[7].AsTypeAliasDeclaration().Type()) assert.Equal(t, defaultClause, defaultReference) } diff --git a/tsc/internal/checker/emitresolver.go b/tsc/internal/checker/emitresolver.go index 4953359de14da..4869ad33dbb10 100644 --- a/tsc/internal/checker/emitresolver.go +++ b/tsc/internal/checker/emitresolver.go @@ -113,7 +113,7 @@ func (r *EmitResolver) GetEnumMemberValue(node *ast.Node) evaluator.Result { r.checkerMu.Lock() defer r.checkerMu.Unlock() - r.checker.computeEnumMemberValues(node.Parent) + r.checker.computeEnumMemberValues(node.Parent()) if !r.checker.enumMemberLinks.Has(node) { return evaluator.NewResult(nil, false, false, false) } @@ -141,8 +141,8 @@ func (r *EmitResolver) PrecalculateDeclarationEmitVisibility(file *ast.SourceFil } func isCommonJSModuleExports(node *ast.Node) bool { - if ast.IsBinaryExpression(node) && ast.IsExpressionStatement(node.Parent) && ast.IsSourceFile(node.Parent.Parent) && - node.Parent.Parent.AsSourceFile().CommonJSModuleIndicator != nil { + if ast.IsBinaryExpression(node) && ast.IsExpressionStatement(node.Parent()) && ast.IsSourceFile(node.Parent().Parent()) && + node.Parent().Parent().AsSourceFile().CommonJSModuleIndicator != nil { switch ast.GetAssignmentDeclarationKind(node) { case ast.JSDeclarationKindModuleExports, ast.JSDeclarationKindExportsProperty: return true @@ -154,8 +154,8 @@ func isCommonJSModuleExports(node *ast.Node) bool { func (r *EmitResolver) aliasMarkingVisitorWorker(node *ast.Node) bool { switch node.Kind { case ast.KindBinaryExpression: - if isCommonJSModuleExports(node) && ast.IsIdentifier(node.AsBinaryExpression().Right) { - r.markLinkedAliases(node.AsBinaryExpression().Right) + if isCommonJSModuleExports(node) && ast.IsIdentifier(node.AsBinaryExpression().Right()) { + r.markLinkedAliases(node.AsBinaryExpression().Right()) } case ast.KindExportAssignment: if node.Expression().Kind == ast.KindIdentifier { @@ -171,10 +171,10 @@ func (r *EmitResolver) aliasMarkingVisitorWorker(node *ast.Node) bool { // Follows chains of import d = a.b.c func (r *EmitResolver) markLinkedAliases(node *ast.Node) { var exportSymbol *ast.Symbol - if node.Kind != ast.KindStringLiteral && node.Parent != nil && (ast.IsExportAssignment(node.Parent) || isCommonJSModuleExports(node.Parent)) { + if node.Kind != ast.KindStringLiteral && node.Parent() != nil && (ast.IsExportAssignment(node.Parent()) || isCommonJSModuleExports(node.Parent())) { 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) + } else if node.Parent().Kind == ast.KindExportSpecifier { + exportSymbol = r.checker.getTargetOfExportSpecifier(node.Parent(), ast.SymbolFlagsValue|ast.SymbolFlagsType|ast.SymbolFlagsNamespace|ast.SymbolFlagsAlias, false) } visited := make(map[ast.SymbolId]struct{}, 2) // guard against circular imports @@ -191,7 +191,7 @@ func (r *EmitResolver) markLinkedAliases(node *ast.Node) { if ast.IsInternalModuleImportEqualsDeclaration(declaration) { // Add the referenced top container visible - internalModuleReference := declaration.AsImportEqualsDeclaration().ModuleReference + internalModuleReference := declaration.AsImportEqualsDeclaration().ModuleReference() firstIdentifier := ast.GetFirstIdentifier(internalModuleReference) importSymbol := r.checker.resolveName(declaration, firstIdentifier.Text(), ast.SymbolFlagsValue|ast.SymbolFlagsType|ast.SymbolFlagsNamespace|ast.SymbolFlagsAlias /*nameNotFoundMessage*/, nil /*isUse*/, false, false) nextSymbol = importSymbol @@ -435,7 +435,7 @@ func (r *EmitResolver) isValueAliasDeclarationWorker(node *ast.Node) bool { symbol := c.getSymbolOfDeclaration(node) return symbol != nil && r.isAliasResolvedToValue(symbol, true /*excludeTypeOnlyValues*/) case ast.KindExportDeclaration: - exportClause := node.AsExportDeclaration().ExportClause + exportClause := node.AsExportDeclaration().ExportClause() return exportClause != nil && (ast.IsNamespaceExport(exportClause) || core.Some(exportClause.Elements(), r.isValueAliasDeclaration)) case ast.KindExportAssignment: @@ -444,7 +444,7 @@ func (r *EmitResolver) isValueAliasDeclarationWorker(node *ast.Node) bool { } return true case ast.KindBinaryExpression: - if isCommonJSModuleExports(node) && ast.IsIdentifier(node.AsBinaryExpression().Right) { + if isCommonJSModuleExports(node) && ast.IsIdentifier(node.AsBinaryExpression().Right()) { return r.isAliasResolvedToValue(c.getSymbolOfDeclaration(node), true /*excludeTypeOnlyValues*/) } } @@ -481,11 +481,11 @@ func (r *EmitResolver) IsTopLevelValueImportEqualsWithEntityName(node *ast.Node) if !c.canCollectSymbolAliasAccessibilityData { return true } - if !ast.IsParseTreeNode(node) || node.Kind != ast.KindImportEqualsDeclaration || node.Parent.Kind != ast.KindSourceFile { + if !ast.IsParseTreeNode(node) || node.Kind != ast.KindImportEqualsDeclaration || node.Parent().Kind != ast.KindSourceFile { return false } if ast.IsImportEqualsDeclaration(node) && - (ast.NodeIsMissing(node.AsImportEqualsDeclaration().ModuleReference) || node.AsImportEqualsDeclaration().ModuleReference.Kind == ast.KindExternalModuleReference) { + (ast.NodeIsMissing(node.AsImportEqualsDeclaration().ModuleReference()) || node.AsImportEqualsDeclaration().ModuleReference().Kind == ast.KindExternalModuleReference) { return false } diff --git a/tsc/internal/checker/emitsupport.go b/tsc/internal/checker/emitsupport.go index 37e08a0052b46..6d1ad535ee784 100644 --- a/tsc/internal/checker/emitsupport.go +++ b/tsc/internal/checker/emitsupport.go @@ -35,9 +35,9 @@ func (c *Checker) determineIfDeclarationIsVisible(node *ast.Node) bool { ast.KindJSDocTypedefTag: // Top-level jsdoc type aliases are considered exported // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file - return node.Parent != nil && node.Parent.Parent != nil && node.Parent.Parent.Parent != nil && ast.IsSourceFile(node.Parent.Parent.Parent) + return node.Parent() != nil && node.Parent().Parent() != nil && node.Parent().Parent().Parent() != nil && ast.IsSourceFile(node.Parent().Parent().Parent()) case ast.KindBindingElement: - return c.isDeclarationVisible(node.Parent.Parent) + return c.isDeclarationVisible(node.Parent().Parent()) case ast.KindVariableDeclaration, ast.KindModuleDeclaration, ast.KindClassDeclaration, @@ -80,7 +80,7 @@ func (c *Checker) determineIfDeclarationIsVisible(node *ast.Node) bool { return false } // Public properties/methods are visible if its parents are visible, so: - return c.isDeclarationVisible(node.Parent) + return c.isDeclarationVisible(node.Parent()) case ast.KindConstructor, ast.KindConstructSignature, @@ -98,7 +98,7 @@ func (c *Checker) determineIfDeclarationIsVisible(node *ast.Node) bool { ast.KindIntersectionType, ast.KindParenthesizedType, ast.KindNamedTupleMember: - return c.isDeclarationVisible(node.Parent) + return c.isDeclarationVisible(node.Parent()) // Default binding, import specifier and namespace import is visible // only on demand so by default it is not visible @@ -122,9 +122,9 @@ func (c *Checker) determineIfDeclarationIsVisible(node *ast.Node) bool { // An `export {X}` (without a module specifier) is itself a visible re-export of // the named binding; it contributes to the symbol's external visibility. case ast.KindExportSpecifier: - exportDecl := node.Parent.Parent - if ast.IsExportDeclaration(exportDecl) && exportDecl.AsExportDeclaration().ModuleSpecifier == nil { - return c.isDeclarationVisible(exportDecl.Parent) + exportDecl := node.Parent().Parent() + if ast.IsExportDeclaration(exportDecl) && exportDecl.AsExportDeclaration().ModuleSpecifier() == nil { + return c.isDeclarationVisible(exportDecl.Parent()) } return false @@ -135,19 +135,19 @@ func (c *Checker) determineIfDeclarationIsVisible(node *ast.Node) bool { func getMeaningOfEntityNameReference(entityName *ast.Node) ast.SymbolFlags { // get symbol of the first identifier of the entityName - if entityName.Parent.Kind == ast.KindTypeQuery || - entityName.Parent.Kind == ast.KindExpressionWithTypeArguments && !ast.IsPartOfTypeNode(entityName.Parent) || - entityName.Parent.Kind == ast.KindComputedPropertyName || - entityName.Parent.Kind == ast.KindTypePredicate && entityName.Parent.AsTypePredicateNode().ParameterName == entityName || - entityName.Parent.Kind == ast.KindBinaryExpression { + if entityName.Parent().Kind == ast.KindTypeQuery || + entityName.Parent().Kind == ast.KindExpressionWithTypeArguments && !ast.IsPartOfTypeNode(entityName.Parent()) || + entityName.Parent().Kind == ast.KindComputedPropertyName || + entityName.Parent().Kind == ast.KindTypePredicate && entityName.Parent().AsTypePredicateNode().ParameterName() == entityName || + entityName.Parent().Kind == ast.KindBinaryExpression { // Typeof value return ast.SymbolFlagsValue | ast.SymbolFlagsExportValue } 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.Expression() == entityName) || - (entityName.Parent.Kind == ast.KindElementAccessExpression && entityName.Parent.Expression() == entityName) { + entityName.Parent().Kind == ast.KindImportEqualsDeclaration || + (entityName.Parent().Kind == ast.KindQualifiedName && entityName.Parent().AsQualifiedName().Left() == 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 @@ -225,30 +225,30 @@ func (c *Checker) hasVisibleDeclarations(symbol *ast.Symbol, shouldComputeAliasT anyImportSyntax := getAnyImportSyntax(declaration) if anyImportSyntax != nil && !ast.HasSyntacticModifier(anyImportSyntax, ast.ModifierFlagsExport) && // import clause without export - c.isDeclarationVisible(anyImportSyntax.Parent) { + c.isDeclarationVisible(anyImportSyntax.Parent()) { addVisibleAlias(declaration, anyImportSyntax) continue } - if ast.IsVariableDeclaration(declaration) && ast.IsVariableStatement(declaration.Parent.Parent) && - !ast.HasSyntacticModifier(declaration.Parent.Parent, ast.ModifierFlagsExport) && // unexported variable statement - c.isDeclarationVisible(declaration.Parent.Parent.Parent) { - addVisibleAlias(declaration, declaration.Parent.Parent) + if ast.IsVariableDeclaration(declaration) && ast.IsVariableStatement(declaration.Parent().Parent()) && + !ast.HasSyntacticModifier(declaration.Parent().Parent(), ast.ModifierFlagsExport) && // unexported variable statement + c.isDeclarationVisible(declaration.Parent().Parent().Parent()) { + addVisibleAlias(declaration, declaration.Parent().Parent()) continue } if ast.IsLateVisibilityPaintedStatement(declaration) && // unexported top-level statement !ast.HasSyntacticModifier(declaration, ast.ModifierFlagsExport) && - c.isDeclarationVisible(declaration.Parent) { + c.isDeclarationVisible(declaration.Parent()) { addVisibleAlias(declaration, declaration) continue } if ast.IsBindingElement(declaration) { - if symbol.Flags&ast.SymbolFlagsAlias != 0 && ast.IsInJSFile(declaration) && declaration.Parent != nil && declaration.Parent.Parent != nil && // exported import-like top-level JS require statement - ast.IsVariableDeclaration(declaration.Parent.Parent) && - declaration.Parent.Parent.Parent.Parent != nil && ast.IsVariableStatement(declaration.Parent.Parent.Parent.Parent) && - !ast.HasSyntacticModifier(declaration.Parent.Parent.Parent.Parent, ast.ModifierFlagsExport) && - declaration.Parent.Parent.Parent.Parent.Parent != nil && // check if the thing containing the variable statement is visible (ie, the file) - c.isDeclarationVisible(declaration.Parent.Parent.Parent.Parent.Parent) { - addVisibleAlias(declaration, declaration.Parent.Parent.Parent.Parent) + if symbol.Flags&ast.SymbolFlagsAlias != 0 && ast.IsInJSFile(declaration) && declaration.Parent() != nil && declaration.Parent().Parent() != nil && // exported import-like top-level JS require statement + ast.IsVariableDeclaration(declaration.Parent().Parent()) && + declaration.Parent().Parent().Parent().Parent() != nil && ast.IsVariableStatement(declaration.Parent().Parent().Parent().Parent()) && + !ast.HasSyntacticModifier(declaration.Parent().Parent().Parent().Parent(), ast.ModifierFlagsExport) && + declaration.Parent().Parent().Parent().Parent().Parent() != nil && // check if the thing containing the variable statement is visible (ie, the file) + c.isDeclarationVisible(declaration.Parent().Parent().Parent().Parent().Parent()) { + addVisibleAlias(declaration, declaration.Parent().Parent().Parent().Parent()) continue } if symbol.Flags&ast.SymbolFlagsBlockScopedVariable != 0 { @@ -256,14 +256,14 @@ func (c *Checker) hasVisibleDeclarations(symbol *ast.Symbol, shouldComputeAliasT if ast.IsParameterDeclaration(rootDeclaration) { return nil } - variableStatement := rootDeclaration.Parent.Parent + variableStatement := rootDeclaration.Parent().Parent() if !ast.IsVariableStatement(variableStatement) { return nil } if ast.HasSyntacticModifier(variableStatement, ast.ModifierFlagsExport) { continue // no alias to add, already exported } - if !c.isDeclarationVisible(variableStatement.Parent) { + if !c.isDeclarationVisible(variableStatement.Parent()) { return nil // not visible } addVisibleAlias(declaration, variableStatement) diff --git a/tsc/internal/checker/flow.go b/tsc/internal/checker/flow.go index d08254cc8ef88..f8cf29370e06f 100644 --- a/tsc/internal/checker/flow.go +++ b/tsc/internal/checker/flow.go @@ -108,7 +108,7 @@ func (c *Checker) getFlowTypeOfReferenceEx(reference *ast.Node, declaredType *Ty } else { resultType = c.finalizeEvolvingArrayType(evolvedType) } - if resultType == c.unreachableNeverType || reference.Parent != nil && ast.IsNonNullExpression(reference.Parent) && resultType.flags&TypeFlagsNever == 0 && c.getTypeWithFacts(resultType, TypeFactsNEUndefinedOrNull).flags&TypeFlagsNever != 0 { + if resultType == c.unreachableNeverType || reference.Parent() != nil && ast.IsNonNullExpression(reference.Parent()) && resultType.flags&TypeFlagsNever == 0 && c.getTypeWithFacts(resultType, TypeFactsNEUndefinedOrNull).flags&TypeFlagsNever != 0 { return declaredType } return resultType @@ -266,7 +266,7 @@ func (c *Checker) getTypeAtFlowAssignment(f *FlowState, flow *ast.FlowNode) Flow return FlowType{t: f.declaredType} } // for (const _ in ref) acts as a nonnull on ref - if ast.IsVariableDeclaration(node) && ast.IsForInStatement(node.Parent.Parent) && (c.isMatchingReference(f.reference, node.Parent.Parent.Expression()) || c.optionalChainContainsReference(node.Parent.Parent.Expression(), f.reference)) { + if ast.IsVariableDeclaration(node) && ast.IsForInStatement(node.Parent().Parent()) && (c.isMatchingReference(f.reference, node.Parent().Parent().Expression()) || c.optionalChainContainsReference(node.Parent().Parent().Expression(), f.reference)) { return FlowType{t: c.getNonNullableTypeIfNeeded(c.finalizeEvolvingArrayType(c.getTypeAtFlowNode(f, flow.Antecedent).t))} } // Assignment doesn't affect reference @@ -282,7 +282,7 @@ func (c *Checker) getInitialOrAssignedType(f *FlowState, flow *ast.FlowNode) *Ty func (c *Checker) isEmptyArrayAssignment(node *ast.Node) bool { return ast.IsVariableDeclaration(node) && node.Initializer() != nil && isEmptyArrayLiteral(node.Initializer()) || - !ast.IsBindingElement(node) && ast.IsBinaryExpression(node.Parent) && isEmptyArrayLiteral(node.Parent.AsBinaryExpression().Right) + !ast.IsBindingElement(node) && ast.IsBinaryExpression(node.Parent()) && isEmptyArrayLiteral(node.Parent().AsBinaryExpression().Right()) } func (c *Checker) getTypeAtFlowCall(f *FlowState, flow *ast.FlowNode) FlowType { @@ -341,11 +341,11 @@ func (c *Checker) narrowTypeByAssertion(f *FlowState, t *Type, expr *ast.Node) * return c.unreachableNeverType } if node.Kind == ast.KindBinaryExpression { - if node.AsBinaryExpression().OperatorToken.Kind == ast.KindAmpersandAmpersandToken { - return c.narrowTypeByAssertion(f, c.narrowTypeByAssertion(f, t, node.AsBinaryExpression().Left), node.AsBinaryExpression().Right) + if node.AsBinaryExpression().OperatorToken().Kind == ast.KindAmpersandAmpersandToken { + return c.narrowTypeByAssertion(f, c.narrowTypeByAssertion(f, t, node.AsBinaryExpression().Left()), node.AsBinaryExpression().Right()) } - if node.AsBinaryExpression().OperatorToken.Kind == ast.KindBarBarToken { - return c.getUnionType([]*Type{c.narrowTypeByAssertion(f, t, node.AsBinaryExpression().Left), c.narrowTypeByAssertion(f, t, node.AsBinaryExpression().Right)}) + if node.AsBinaryExpression().OperatorToken().Kind == ast.KindBarBarToken { + return c.getUnionType([]*Type{c.narrowTypeByAssertion(f, t, node.AsBinaryExpression().Left()), c.narrowTypeByAssertion(f, t, node.AsBinaryExpression().Right())}) } } return c.narrowType(f, t, node, true /*assumeTrue*/) @@ -376,7 +376,7 @@ func (c *Checker) getTypeAtFlowCondition(f *FlowState, flow *ast.FlowNode) FlowT // will be a subtype or the same type as the argument. func (c *Checker) narrowType(f *FlowState, t *Type, expr *ast.Node, assumeTrue bool) *Type { // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a` - if ast.IsExpressionOfOptionalChainRoot(expr) || ast.IsBinaryExpression(expr.Parent) && (expr.Parent.AsBinaryExpression().OperatorToken.Kind == ast.KindQuestionQuestionToken || expr.Parent.AsBinaryExpression().OperatorToken.Kind == ast.KindQuestionQuestionEqualsToken) && expr.Parent.AsBinaryExpression().Left == expr { + if ast.IsExpressionOfOptionalChainRoot(expr) || ast.IsBinaryExpression(expr.Parent()) && (expr.Parent().AsBinaryExpression().OperatorToken().Kind == ast.KindQuestionQuestionToken || expr.Parent().AsBinaryExpression().OperatorToken().Kind == ast.KindQuestionQuestionEqualsToken) && expr.Parent().AsBinaryExpression().Left() == expr { return c.narrowTypeByOptionality(f, t, expr, assumeTrue) } switch expr.Kind { @@ -406,7 +406,7 @@ func (c *Checker) narrowType(f *FlowState, t *Type, expr *ast.Node, assumeTrue b return c.narrowTypeByBinaryExpression(f, t, expr.AsBinaryExpression(), assumeTrue) case ast.KindPrefixUnaryExpression: if expr.AsPrefixUnaryExpression().Operator == ast.KindExclamationToken { - return c.narrowType(f, t, expr.AsPrefixUnaryExpression().Operand, !assumeTrue) + return c.narrowType(f, t, expr.AsPrefixUnaryExpression().Operand(), !assumeTrue) } } return t @@ -467,13 +467,13 @@ func (c *Checker) narrowTypeByCallExpression(f *FlowState, t *Type, callExpressi } func (c *Checker) narrowTypeByBinaryExpression(f *FlowState, t *Type, expr *ast.BinaryExpression, assumeTrue bool) *Type { - switch expr.OperatorToken.Kind { + switch expr.OperatorToken().Kind { case ast.KindEqualsToken, ast.KindBarBarEqualsToken, ast.KindAmpersandAmpersandEqualsToken, ast.KindQuestionQuestionEqualsToken: - return c.narrowTypeByTruthiness(f, c.narrowType(f, t, expr.Right, assumeTrue), expr.Left, assumeTrue) + return c.narrowTypeByTruthiness(f, c.narrowType(f, t, expr.Right(), assumeTrue), expr.Left(), assumeTrue) case ast.KindEqualsEqualsToken, ast.KindExclamationEqualsToken, ast.KindEqualsEqualsEqualsToken, ast.KindExclamationEqualsEqualsToken: - operator := expr.OperatorToken.Kind - left := c.getReferenceCandidate(expr.Left) - right := c.getReferenceCandidate(expr.Right) + operator := expr.OperatorToken().Kind + left := c.getReferenceCandidate(expr.Left()) + right := c.getReferenceCandidate(expr.Right()) if left.Kind == ast.KindTypeOfExpression && ast.IsStringLiteralLike(right) { return c.narrowTypeByTypeof(f, t, left.AsTypeOfExpression(), operator, right, assumeTrue) } @@ -516,12 +516,12 @@ func (c *Checker) narrowTypeByBinaryExpression(f *FlowState, t *Type, expr *ast. case ast.KindInstanceOfKeyword: return c.narrowTypeByInstanceof(f, t, expr, assumeTrue) case ast.KindInKeyword: - if ast.IsPrivateIdentifier(expr.Left) { + if ast.IsPrivateIdentifier(expr.Left()) { return c.narrowTypeByPrivateIdentifierInInExpression(f, t, expr, assumeTrue) } - target := c.getReferenceCandidate(expr.Right) + target := c.getReferenceCandidate(expr.Right()) if c.containsMissingType(t) && ast.IsAccessExpression(f.reference) && c.isMatchingReference(f.reference.Expression(), target) { - leftType := c.getTypeOfExpression(expr.Left) + leftType := c.getTypeOfExpression(expr.Left()) if isTypeUsableAsPropertyName(leftType) { if accessedName, ok := c.getAccessedPropertyName(f.reference); ok && accessedName == getPropertyNameFromType(leftType) { return c.getTypeWithFacts(t, core.IfElse(assumeTrue, TypeFactsNEUndefined, TypeFactsEQUndefined)) @@ -529,26 +529,26 @@ func (c *Checker) narrowTypeByBinaryExpression(f *FlowState, t *Type, expr *ast. } } if c.isMatchingReference(f.reference, target) { - leftType := c.getTypeOfExpression(expr.Left) + leftType := c.getTypeOfExpression(expr.Left()) if isTypeUsableAsPropertyName(leftType) { return c.narrowTypeByInKeyword(f, t, leftType, assumeTrue) } } case ast.KindCommaToken: - return c.narrowType(f, t, expr.Right, assumeTrue) + return c.narrowType(f, t, expr.Right(), assumeTrue) case ast.KindAmpersandAmpersandToken: // Ordinarily we won't see && and || expressions in control flow analysis because the Binder breaks those // expressions down to individual conditional control flows. However, we may encounter them when analyzing // aliased conditional expressions. if assumeTrue { - return c.narrowType(f, c.narrowType(f, t, expr.Left, true /*assumeTrue*/), expr.Right, true /*assumeTrue*/) + return c.narrowType(f, c.narrowType(f, t, expr.Left(), true /*assumeTrue*/), expr.Right(), true /*assumeTrue*/) } - return c.getUnionType([]*Type{c.narrowType(f, t, expr.Left, false /*assumeTrue*/), c.narrowType(f, t, expr.Right, false /*assumeTrue*/)}) + return c.getUnionType([]*Type{c.narrowType(f, t, expr.Left(), false /*assumeTrue*/), c.narrowType(f, t, expr.Right(), false /*assumeTrue*/)}) case ast.KindBarBarToken: if assumeTrue { - return c.getUnionType([]*Type{c.narrowType(f, t, expr.Left, true /*assumeTrue*/), c.narrowType(f, t, expr.Right, true /*assumeTrue*/)}) + return c.getUnionType([]*Type{c.narrowType(f, t, expr.Left(), true /*assumeTrue*/), c.narrowType(f, t, expr.Right(), true /*assumeTrue*/)}) } - return c.narrowType(f, c.narrowType(f, t, expr.Left, false /*assumeTrue*/), expr.Right, false /*assumeTrue*/) + return c.narrowType(f, c.narrowType(f, t, expr.Left(), false /*assumeTrue*/), expr.Right(), false /*assumeTrue*/) } return t } @@ -616,7 +616,7 @@ func (c *Checker) narrowTypeByTypeof(f *FlowState, t *Type, typeOfExpr *ast.Type if operator == ast.KindExclamationEqualsToken || operator == ast.KindExclamationEqualsEqualsToken { assumeTrue = !assumeTrue } - target := c.getReferenceCandidate(typeOfExpr.Expression) + target := c.getReferenceCandidate(typeOfExpr.Expression()) if !c.isMatchingReference(f.reference, target) { if c.strictNullChecks && c.optionalChainContainsReference(target, f.reference) && assumeTrue == (literal.Text() != "undefined") { t = c.getAdjustedTypeWithFacts(t, TypeFactsNEUndefinedOrNull) @@ -751,8 +751,8 @@ func (c *Checker) isMatchingConstructorReference(f *FlowState, expr *ast.Node) b var name *ast.Node if ast.IsPropertyAccessExpression(expr) { name = expr.AsPropertyAccessExpression().Name() - } else if ast.IsElementAccessExpression(expr) && ast.IsStringLiteralLike(expr.AsElementAccessExpression().ArgumentExpression) { - name = expr.AsElementAccessExpression().ArgumentExpression + } else if ast.IsElementAccessExpression(expr) && ast.IsStringLiteralLike(expr.AsElementAccessExpression().ArgumentExpression()) { + name = expr.AsElementAccessExpression().ArgumentExpression() } return name != nil && name.Text() == "constructor" && c.isMatchingReference(f.reference, expr.Expression()) } @@ -809,14 +809,14 @@ func (c *Checker) narrowTypeByBooleanComparison(f *FlowState, t *Type, expr *ast } func (c *Checker) narrowTypeByInstanceof(f *FlowState, t *Type, expr *ast.BinaryExpression, assumeTrue bool) *Type { - left := c.getReferenceCandidate(expr.Left) + left := c.getReferenceCandidate(expr.Left()) if !c.isMatchingReference(f.reference, left) { if assumeTrue && c.strictNullChecks && c.optionalChainContainsReference(left, f.reference) { return c.getAdjustedTypeWithFacts(t, TypeFactsNEUndefinedOrNull) } return t } - right := expr.Right + right := expr.Right() rightType := c.getTypeOfExpression(right) if !c.isTypeDerivedFrom(rightType, c.globalObjectType) { return t @@ -980,11 +980,11 @@ func (c *Checker) getInstanceType(constructorType *Type) *Type { } func (c *Checker) narrowTypeByPrivateIdentifierInInExpression(f *FlowState, t *Type, expr *ast.BinaryExpression, assumeTrue bool) *Type { - target := c.getReferenceCandidate(expr.Right) + target := c.getReferenceCandidate(expr.Right()) if !c.isMatchingReference(f.reference, target) { return t } - symbol := c.getSymbolForPrivateIdentifierExpression(expr.Left) + symbol := c.getSymbolForPrivateIdentifierExpression(expr.Left()) if symbol == nil { return t } @@ -1159,7 +1159,7 @@ func (c *Checker) narrowTypeBySwitchOnTypeOf(t *Type, data *ast.FlowSwitchClause if witnesses == nil { return t } - clauses := data.SwitchStatement.AsSwitchStatement().CaseBlock.AsCaseBlock().Clauses.Nodes + clauses := data.SwitchStatement.AsSwitchStatement().CaseBlock().AsCaseBlock().Clauses().Nodes // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause. defaultIndex := core.FindIndex(clauses, func(clause *ast.Node) bool { return clause.Kind == ast.KindDefaultClause @@ -1185,7 +1185,7 @@ func (c *Checker) narrowTypeBySwitchOnTypeOf(t *Type, data *ast.FlowSwitchClause } func (c *Checker) narrowTypeBySwitchOnTrue(f *FlowState, t *Type, data *ast.FlowSwitchClauseData) *Type { - clauses := data.SwitchStatement.AsSwitchStatement().CaseBlock.AsCaseBlock().Clauses.Nodes + clauses := data.SwitchStatement.AsSwitchStatement().CaseBlock().AsCaseBlock().Clauses().Nodes defaultIndex := core.FindIndex(clauses, func(clause *ast.Node) bool { return clause.Kind == ast.KindDefaultClause }) @@ -1408,7 +1408,7 @@ func (c *Checker) getTypeAtFlowArrayMutation(f *FlowState, flow *ast.FlowNode) F if ast.IsCallExpression(node) { expr = node.Expression().Expression() } else { - expr = node.AsBinaryExpression().Left.Expression() + expr = node.AsBinaryExpression().Left().Expression() } if c.isMatchingReference(f.reference, c.getReferenceCandidate(expr)) { flowType := c.getTypeAtFlowNode(f, flow.Antecedent) @@ -1420,9 +1420,9 @@ func (c *Checker) getTypeAtFlowArrayMutation(f *FlowState, flow *ast.FlowNode) F } } else { // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) - indexType := c.getContextFreeTypeOfExpression(node.AsBinaryExpression().Left.AsElementAccessExpression().ArgumentExpression) + indexType := c.getContextFreeTypeOfExpression(node.AsBinaryExpression().Left().AsElementAccessExpression().ArgumentExpression()) if c.isTypeAssignableToKind(indexType, TypeFlagsNumberLike) { - evolvedType = c.addEvolvingArrayElementType(evolvedType, node.AsBinaryExpression().Right) + evolvedType = c.addEvolvingArrayElementType(evolvedType, node.AsBinaryExpression().Right()) } } return c.newFlowType(evolvedType, flowType.incomplete) @@ -1463,7 +1463,7 @@ func (c *Checker) getCandidateDiscriminantPropertyAccess(f *FlowState, expr *ast if ast.IsIdentifier(expr) { symbol := c.getResolvedSymbol(expr) declaration := c.getExportSymbolOfValueSymbolIfExported(symbol).ValueDeclaration - if declaration != nil && (ast.IsBindingElement(declaration) || ast.IsParameterDeclaration(declaration)) && f.reference == declaration.Parent && declaration.Initializer() == nil && !hasDotDotDotToken(declaration) { + if declaration != nil && (ast.IsBindingElement(declaration) || ast.IsParameterDeclaration(declaration)) && f.reference == declaration.Parent() && declaration.Initializer() == nil && !hasDotDotDotToken(declaration) { return declaration } } @@ -1483,7 +1483,7 @@ func (c *Checker) getCandidateDiscriminantPropertyAccess(f *FlowState, expr *ast } // Given 'const { kind: x } = obj', allow 'x' as an alias for 'obj.kind' if ast.IsBindingElement(declaration) && declaration.Initializer() == nil { - initializer = getCandidateVariableDeclarationInitializer(declaration.Parent.Parent) + initializer = getCandidateVariableDeclarationInitializer(declaration.Parent().Parent()) if initializer != nil && (ast.IsIdentifier(initializer) || ast.IsAccessExpression(initializer)) && c.isMatchingReference(f.reference, initializer) { return declaration } @@ -1541,13 +1541,13 @@ func isEvolvingArrayTypeList(types []*Type) bool { // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type. func (c *Checker) isEvolvingArrayOperationTarget(node *ast.Node) bool { root := c.getReferenceRoot(node) - parent := root.Parent + parent := root.Parent() isLengthPushOrUnshift := ast.IsPropertyAccessExpression(parent) && (parent.Name().Text() == "length" || - ast.IsCallExpression(parent.Parent) && ast.IsIdentifier(parent.Name()) && ast.IsPushOrUnshiftIdentifier(parent.Name())) + ast.IsCallExpression(parent.Parent()) && ast.IsIdentifier(parent.Name()) && ast.IsPushOrUnshiftIdentifier(parent.Name())) isElementAssignment := ast.IsElementAccessExpression(parent) && parent.Expression() == root && - ast.IsBinaryExpression(parent.Parent) && parent.Parent.AsBinaryExpression().OperatorToken.Kind == ast.KindEqualsToken && - parent.Parent.AsBinaryExpression().Left == parent && !ast.IsAssignmentTarget(parent.Parent) && - c.isTypeAssignableToKind(c.getTypeOfExpression(parent.AsElementAccessExpression().ArgumentExpression), TypeFlagsNumberLike) + ast.IsBinaryExpression(parent.Parent()) && parent.Parent().AsBinaryExpression().OperatorToken().Kind == ast.KindEqualsToken && + parent.Parent().AsBinaryExpression().Left() == parent && !ast.IsAssignmentTarget(parent.Parent()) && + c.isTypeAssignableToKind(c.getTypeOfExpression(parent.AsElementAccessExpression().ArgumentExpression()), TypeFlagsNumberLike) return isLengthPushOrUnshift || isElementAssignment } @@ -1599,9 +1599,9 @@ func (c *Checker) isMatchingReference(source *ast.Node, target *ast.Node) bool { case ast.KindParenthesizedExpression, ast.KindNonNullExpression: return c.isMatchingReference(source, target.Expression()) case ast.KindBinaryExpression: - return ast.IsAssignmentExpression(target, false) && c.isMatchingReference(source, target.AsBinaryExpression().Left) || - ast.IsBinaryExpression(target) && target.AsBinaryExpression().OperatorToken.Kind == ast.KindCommaToken && - c.isMatchingReference(source, target.AsBinaryExpression().Right) + return ast.IsAssignmentExpression(target, false) && c.isMatchingReference(source, target.AsBinaryExpression().Left()) || + ast.IsBinaryExpression(target) && target.AsBinaryExpression().OperatorToken().Kind == ast.KindCommaToken && + c.isMatchingReference(source, target.AsBinaryExpression().Right()) } switch source.Kind { case ast.KindMetaProperty: @@ -1627,8 +1627,8 @@ func (c *Checker) isMatchingReference(source *ast.Node, target *ast.Node) bool { } } if ast.IsElementAccessExpression(source) && ast.IsElementAccessExpression(target) { - sourceArg := source.AsElementAccessExpression().ArgumentExpression - targetArg := target.AsElementAccessExpression().ArgumentExpression + sourceArg := source.AsElementAccessExpression().ArgumentExpression() + targetArg := target.AsElementAccessExpression().ArgumentExpression() if ast.IsIdentifier(sourceArg) && ast.IsIdentifier(targetArg) { symbol := c.getResolvedSymbol(sourceArg) if symbol == c.getResolvedSymbol(targetArg) && (c.isConstantVariable(symbol) || c.isParameterOrMutableLocalVariable(symbol) && !c.isSymbolAssigned(symbol)) { @@ -1639,11 +1639,11 @@ func (c *Checker) isMatchingReference(source *ast.Node, target *ast.Node) bool { case ast.KindQualifiedName: if ast.IsAccessExpression(target) { if targetPropertyName, ok := c.getAccessedPropertyName(target); ok { - return source.AsQualifiedName().Right.Text() == targetPropertyName && c.isMatchingReference(source.AsQualifiedName().Left, target.Expression()) + return source.AsQualifiedName().Right().Text() == targetPropertyName && c.isMatchingReference(source.AsQualifiedName().Left(), target.Expression()) } } case ast.KindBinaryExpression: - return ast.IsBinaryExpression(source) && source.AsBinaryExpression().OperatorToken.Kind == ast.KindCommaToken && c.isMatchingReference(source.AsBinaryExpression().Right, target) + return ast.IsBinaryExpression(source) && source.AsBinaryExpression().OperatorToken().Kind == ast.KindCommaToken && c.isMatchingReference(source.AsBinaryExpression().Right(), target) } return false } @@ -1688,11 +1688,11 @@ func (c *Checker) writeFlowCacheKey(b *keyBuilder, node *ast.Node, declaredType case ast.KindNonNullExpression, ast.KindParenthesizedExpression: return c.writeFlowCacheKey(b, node.Expression(), declaredType, initialType, flowContainer) case ast.KindQualifiedName: - if !c.writeFlowCacheKey(b, node.AsQualifiedName().Left, declaredType, initialType, flowContainer) { + if !c.writeFlowCacheKey(b, node.AsQualifiedName().Left(), declaredType, initialType, flowContainer) { return false } b.writeByte('.') - b.writeString(node.AsQualifiedName().Right.Text()) + b.writeString(node.AsQualifiedName().Right().Text()) return true case ast.KindPropertyAccessExpression, ast.KindElementAccessExpression: if propName, ok := c.getAccessedPropertyName(node); ok { @@ -1703,8 +1703,8 @@ func (c *Checker) writeFlowCacheKey(b *keyBuilder, node *ast.Node, declaredType b.writeString(propName) return true } - if ast.IsElementAccessExpression(node) && ast.IsIdentifier(node.AsElementAccessExpression().ArgumentExpression) { - symbol := c.getResolvedSymbol(node.AsElementAccessExpression().ArgumentExpression) + if ast.IsElementAccessExpression(node) && ast.IsIdentifier(node.AsElementAccessExpression().ArgumentExpression()) { + symbol := c.getResolvedSymbol(node.AsElementAccessExpression().ArgumentExpression()) if c.isConstantVariable(symbol) || c.isParameterOrMutableLocalVariable(symbol) && !c.isSymbolAssigned(symbol) { if !c.writeFlowCacheKey(b, node.Expression(), declaredType, initialType, flowContainer) { return false @@ -1735,17 +1735,17 @@ func (c *Checker) getAccessedPropertyName(access *ast.Node) (string, bool) { return c.getDestructuringPropertyName(access) } if ast.IsParameterDeclaration(access) { - return strconv.Itoa(slices.Index(access.Parent.Parameters(), access)), true + return strconv.Itoa(slices.Index(access.Parent().Parameters(), access)), true } return "", false } func (c *Checker) tryGetElementAccessExpressionName(node *ast.ElementAccessExpression) (string, bool) { switch { - case ast.IsStringOrNumericLiteralLike(node.ArgumentExpression): - return node.ArgumentExpression.Text(), true - case ast.IsEntityNameExpression(node.ArgumentExpression): - return c.tryGetNameFromEntityNameExpression(node.ArgumentExpression) + case ast.IsStringOrNumericLiteralLike(node.ArgumentExpression()): + return node.ArgumentExpression().Text(), true + case ast.IsEntityNameExpression(node.ArgumentExpression()): + return c.tryGetNameFromEntityNameExpression(node.ArgumentExpression()) } return "", false } @@ -1790,7 +1790,7 @@ func tryGetNameFromType(t *Type) (string, bool) { } func (c *Checker) getDestructuringPropertyName(node *ast.Node) (string, bool) { - parent := node.Parent + parent := node.Parent() if ast.IsBindingElement(node) && ast.IsObjectBindingPattern(parent) { return c.getLiteralPropertyNameText(getBindingElementPropertyName(node)) } @@ -1829,8 +1829,8 @@ func (c *Checker) isConstantReference(node *ast.Node) bool { } } case ast.KindObjectBindingPattern, ast.KindArrayBindingPattern: - rootDeclaration := ast.GetRootDeclaration(node.Parent) - if ast.IsParameterDeclaration(rootDeclaration) || ast.IsVariableDeclaration(rootDeclaration) && ast.IsCatchClause(rootDeclaration.Parent) { + rootDeclaration := ast.GetRootDeclaration(node.Parent()) + if ast.IsParameterDeclaration(rootDeclaration) || ast.IsVariableDeclaration(rootDeclaration) && ast.IsCatchClause(rootDeclaration.Parent()) { return !c.isSomeSymbolAssigned(rootDeclaration) } return ast.IsVariableDeclaration(rootDeclaration) && c.isVarConstLike(rootDeclaration) @@ -1863,21 +1863,21 @@ func (c *Checker) getReferenceCandidate(node *ast.Node) *ast.Node { case ast.KindParenthesizedExpression: return c.getReferenceCandidate(node.Expression()) case ast.KindBinaryExpression: - switch node.AsBinaryExpression().OperatorToken.Kind { + switch node.AsBinaryExpression().OperatorToken().Kind { case ast.KindEqualsToken, ast.KindBarBarEqualsToken, ast.KindAmpersandAmpersandEqualsToken, ast.KindQuestionQuestionEqualsToken: - return c.getReferenceCandidate(node.AsBinaryExpression().Left) + return c.getReferenceCandidate(node.AsBinaryExpression().Left()) case ast.KindCommaToken: - return c.getReferenceCandidate(node.AsBinaryExpression().Right) + return c.getReferenceCandidate(node.AsBinaryExpression().Right()) } } return node } func (c *Checker) getReferenceRoot(node *ast.Node) *ast.Node { - parent := node.Parent + parent := node.Parent() if ast.IsParenthesizedExpression(parent) || - ast.IsBinaryExpression(parent) && parent.AsBinaryExpression().OperatorToken.Kind == ast.KindEqualsToken && parent.AsBinaryExpression().Left == node || - ast.IsBinaryExpression(parent) && parent.AsBinaryExpression().OperatorToken.Kind == ast.KindCommaToken && parent.AsBinaryExpression().Right == node { + ast.IsBinaryExpression(parent) && parent.AsBinaryExpression().OperatorToken().Kind == ast.KindEqualsToken && parent.AsBinaryExpression().Left() == node || + ast.IsBinaryExpression(parent) && parent.AsBinaryExpression().OperatorToken().Kind == ast.KindCommaToken && parent.AsBinaryExpression().Right() == node { return c.getReferenceRoot(parent) } return node @@ -1989,7 +1989,7 @@ func (c *Checker) eachTypeContainedIn(source *Type, types []*Type) bool { func (c *Checker) getSwitchClauseTypeOfWitnesses(node *ast.Node) []string { links := c.switchStatementLinks.Get(node) if !links.witnessesComputed { - clauses := node.AsSwitchStatement().CaseBlock.AsCaseBlock().Clauses.Nodes + clauses := node.AsSwitchStatement().CaseBlock().AsCaseBlock().Clauses().Nodes witnesses := make([]string, len(clauses)) for i, clause := range clauses { if clause.Kind == ast.KindCaseClause { @@ -2026,7 +2026,7 @@ func (c *Checker) getNotEqualFactsFromTypeofSwitch(start int, end int, witnesses func (c *Checker) getSwitchClauseTypes(node *ast.Node) []*Type { links := c.switchStatementLinks.Get(node) if !links.switchTypesComputed { - clauses := node.AsSwitchStatement().CaseBlock.AsCaseBlock().Clauses.Nodes + clauses := node.AsSwitchStatement().CaseBlock().AsCaseBlock().Clauses().Nodes types := make([]*Type, len(clauses)) for i, clause := range clauses { types[i] = c.getTypeOfSwitchClause(clause) @@ -2054,9 +2054,9 @@ func (c *Checker) getEffectsSignature(node *ast.Node) *Signature { // target expression of an assertion. var funcType *Type if ast.IsBinaryExpression(node) { - rightType := c.checkNonNullExpression(node.AsBinaryExpression().Right) + rightType := c.checkNonNullExpression(node.AsBinaryExpression().Right()) funcType = c.getSymbolHasInstanceMethodOfObjectType(rightType) - } else if ast.IsExpressionStatement(node.Parent) { + } else if ast.IsExpressionStatement(node.Parent()) { funcType = c.getTypeOfDottedName(node.Expression(), nil /*diagnostic*/) } else if node.Expression().Kind != ast.KindSuperKeyword { if ast.IsOptionalChain(node) { @@ -2173,12 +2173,12 @@ func (c *Checker) getExplicitTypeOfSymbol(symbol *ast.Symbol, diagnostic *ast.Di if c.isDeclarationWithExplicitTypeAnnotation(declaration) { return c.getTypeOfSymbol(symbol) } - if ast.IsVariableDeclaration(declaration) && ast.IsForOfStatement(declaration.Parent.Parent) { - statement := declaration.Parent.Parent + if ast.IsVariableDeclaration(declaration) && ast.IsForOfStatement(declaration.Parent().Parent()) { + statement := declaration.Parent().Parent() expressionType := c.getTypeOfDottedName(statement.Expression(), nil /*diagnostic*/) if expressionType != nil { var use IterationUse - if statement.AsForInOrOfStatement().AwaitModifier != nil { + if statement.AsForInOrOfStatement().AwaitModifier() != nil { use = IterationUseForAwaitOf } else { use = IterationUseForOf @@ -2201,7 +2201,7 @@ func (c *Checker) isDeclarationWithExplicitTypeAnnotation(node *ast.Node) bool { func (c *Checker) isExpandoPropertyFunctionWithReturnTypeAnnotation(node *ast.Node) bool { if ast.IsBinaryExpression(node) { - if expr := node.AsBinaryExpression().Right; ast.IsFunctionLike(expr) && expr.Type() != nil { + if expr := node.AsBinaryExpression().Right(); ast.IsFunctionLike(expr) && expr.Type() != nil { return true } } @@ -2220,8 +2220,8 @@ func (c *Checker) getExplicitThisType(node *ast.Node) *Type { return c.getExplicitTypeOfSymbol(signature.thisParameter, nil) } } - if container.Parent != nil && ast.IsClassLike(container.Parent) { - symbol := c.getSymbolOfDeclaration(container.Parent) + if container.Parent() != nil && ast.IsClassLike(container.Parent()) { + symbol := c.getSymbolOfDeclaration(container.Parent()) if ast.IsStatic(container) { return c.getTypeOfSymbol(symbol) } else { @@ -2245,11 +2245,11 @@ func (c *Checker) getInitialTypeOfVariableDeclaration(node *ast.Node) *Type { if node.Initializer() != nil { return c.getTypeOfInitializer(node.Initializer()) } - if ast.IsForInStatement(node.Parent.Parent) { + if ast.IsForInStatement(node.Parent().Parent()) { return c.stringType } - if ast.IsForOfStatement(node.Parent.Parent) { - t := c.checkRightHandSideOfForOf(node.Parent.Parent) + if ast.IsForOfStatement(node.Parent().Parent()) { + t := c.checkRightHandSideOfForOf(node.Parent().Parent()) if t != nil { return t } @@ -2271,8 +2271,8 @@ func (c *Checker) getTypeOfInitializer(node *ast.Node) *Type { } func (c *Checker) getInitialTypeOfBindingElement(node *ast.Node) *Type { - pattern := node.Parent - parentType := c.getInitialType(pattern.Parent) + pattern := node.Parent() + parentType := c.getInitialType(pattern.Parent()) var t *Type switch { case ast.IsObjectBindingPattern(pattern): @@ -2286,7 +2286,7 @@ func (c *Checker) getInitialTypeOfBindingElement(node *ast.Node) *Type { } func (c *Checker) getAssignedType(node *ast.Node) *Type { - parent := node.Parent + parent := node.Parent() switch parent.Kind { case ast.KindForInStatement: return c.stringType @@ -2312,12 +2312,12 @@ func (c *Checker) getAssignedType(node *ast.Node) *Type { } func (c *Checker) getAssignedTypeOfBinaryExpression(node *ast.Node) *Type { - isDestructuringDefaultAssignment := ast.IsArrayLiteralExpression(node.Parent) && c.isDestructuringAssignmentTarget(node.Parent) || - ast.IsPropertyAssignment(node.Parent) && c.isDestructuringAssignmentTarget(node.Parent.Parent) + isDestructuringDefaultAssignment := ast.IsArrayLiteralExpression(node.Parent()) && c.isDestructuringAssignmentTarget(node.Parent()) || + ast.IsPropertyAssignment(node.Parent()) && c.isDestructuringAssignmentTarget(node.Parent().Parent()) if isDestructuringDefaultAssignment { - return c.getTypeWithDefault(c.getAssignedType(node), node.AsBinaryExpression().Right) + return c.getTypeWithDefault(c.getAssignedType(node), node.AsBinaryExpression().Right()) } - return c.getTypeOfExpression(node.AsBinaryExpression().Right) + return c.getTypeOfExpression(node.AsBinaryExpression().Right()) } func (c *Checker) getAssignedTypeOfArrayLiteralElement(node *ast.Node, element *ast.Node) *Type { @@ -2347,7 +2347,7 @@ func (c *Checker) includeUndefinedInIndexSignature(t *Type) *Type { } func (c *Checker) getAssignedTypeOfSpreadExpression(node *ast.Node) *Type { - return c.getTypeOfDestructuredSpreadExpression(c.getAssignedType(node.Parent)) + return c.getTypeOfDestructuredSpreadExpression(c.getAssignedType(node.Parent())) } func (c *Checker) getTypeOfDestructuredSpreadExpression(t *Type) *Type { @@ -2359,7 +2359,7 @@ func (c *Checker) getTypeOfDestructuredSpreadExpression(t *Type) *Type { } func (c *Checker) getAssignedTypeOfPropertyAssignment(node *ast.Node) *Type { - return c.getTypeOfDestructuredProperty(c.getAssignedType(node.Parent), node.Name()) + return c.getTypeOfDestructuredProperty(c.getAssignedType(node.Parent()), node.Name()) } func (c *Checker) getTypeOfDestructuredProperty(t *Type, name *ast.Node) *Type { @@ -2378,12 +2378,12 @@ func (c *Checker) getTypeOfDestructuredProperty(t *Type, name *ast.Node) *Type { } func (c *Checker) getAssignedTypeOfShorthandPropertyAssignment(node *ast.Node) *Type { - return c.getTypeWithDefault(c.getAssignedTypeOfPropertyAssignment(node), node.AsShorthandPropertyAssignment().ObjectAssignmentInitializer) + return c.getTypeWithDefault(c.getAssignedTypeOfPropertyAssignment(node), node.AsShorthandPropertyAssignment().ObjectAssignmentInitializer()) } func (c *Checker) isDestructuringAssignmentTarget(parent *ast.Node) bool { - return ast.IsBinaryExpression(parent.Parent) && parent.Parent.AsBinaryExpression().Left == parent || - ast.IsForOfStatement(parent.Parent) && parent.Parent.Initializer() == parent + return ast.IsBinaryExpression(parent.Parent()) && parent.Parent().AsBinaryExpression().Left() == parent || + ast.IsForOfStatement(parent.Parent()) && parent.Parent().Initializer() == parent } func (c *Checker) getTypeWithDefault(t *Type, defaultExpression *ast.Node) *Type { @@ -2471,9 +2471,9 @@ func (c *Checker) getFlowTypeInConstructor(symbol *ast.Symbol, constructor *ast. accessName = c.factory.NewIdentifier(symbol.Name) } reference := c.factory.NewPropertyAccessExpression(c.factory.NewKeywordExpression(ast.KindThisKeyword), nil, accessName, ast.NodeFlagsNone) - reference.Expression().Parent = reference - reference.Parent = constructor - reference.FlowNodeData().FlowNode = constructor.AsConstructorDeclaration().ReturnFlowNode + reference.Expression().SetParent(reference) + reference.SetParent(constructor) + ast.SetFlowNode(reference, constructor.AsConstructorDeclaration().ReturnFlowNode) flowType := c.getFlowTypeOfProperty(reference, symbol) if c.noImplicitAny && (flowType == c.autoType || flowType == c.autoArrayType) { c.error(symbol.ValueDeclaration, diagnostics.Member_0_implicitly_has_an_1_type, c.symbolToString(symbol), c.TypeToString(flowType)) @@ -2494,9 +2494,9 @@ func (c *Checker) getFlowTypeInStaticBlocks(symbol *ast.Symbol, staticBlocks []* } for _, staticBlock := range staticBlocks { reference := c.factory.NewPropertyAccessExpression(c.factory.NewKeywordExpression(ast.KindThisKeyword), nil, accessName, ast.NodeFlagsNone) - reference.Expression().Parent = reference - reference.Parent = staticBlock - reference.FlowNodeData().FlowNode = staticBlock.AsClassStaticBlockDeclaration().ReturnFlowNode + reference.Expression().SetParent(reference) + reference.SetParent(staticBlock) + ast.SetFlowNode(reference, staticBlock.AsClassStaticBlockDeclaration().ReturnFlowNode) flowType := c.getFlowTypeOfProperty(reference, symbol) if c.noImplicitAny && (flowType == c.autoType || flowType == c.autoArrayType) { c.error(symbol.ValueDeclaration, diagnostics.Member_0_implicitly_has_an_1_type, c.symbolToString(symbol), c.TypeToString(flowType)) @@ -2593,8 +2593,8 @@ func (c *Checker) isFalseExpression(expr *ast.Node) bool { } if ast.IsBinaryExpression(node) { binary := node.AsBinaryExpression() - return binary.OperatorToken.Kind == ast.KindAmpersandAmpersandToken && (c.isFalseExpression(binary.Left) || c.isFalseExpression(binary.Right)) || - binary.OperatorToken.Kind == ast.KindBarBarToken && c.isFalseExpression(binary.Left) && c.isFalseExpression(binary.Right) + return binary.OperatorToken().Kind == ast.KindAmpersandAmpersandToken && (c.isFalseExpression(binary.Left()) || c.isFalseExpression(binary.Right())) || + binary.OperatorToken().Kind == ast.KindBarBarToken && c.isFalseExpression(binary.Left()) && c.isFalseExpression(binary.Right()) } return false } @@ -2686,7 +2686,7 @@ func (c *Checker) ensureAssignmentsMarked(symbol *ast.Symbol) { } func (c *Checker) hasParentWithAssignmentsMarked(node *ast.Node) bool { - return ast.FindAncestor(node.Parent, func(node *ast.Node) bool { + return ast.FindAncestor(node.Parent(), func(node *ast.Node) bool { return ast.IsFunctionOrSourceFile(node) && c.nodeLinks.Get(node).flags&NodeCheckFlagsAssignmentsMarked != 0 }) != nil } @@ -2721,9 +2721,9 @@ func (c *Checker) markNodeAssignmentsWorker(node *ast.Node) bool { } return false case ast.KindExportSpecifier: - exportDeclaration := node.AsExportSpecifier().Parent.Parent.AsExportDeclaration() + exportDeclaration := node.AsExportSpecifier().Parent().Parent().AsExportDeclaration() name := node.PropertyNameOrName() - if !node.IsTypeOnly() && !exportDeclaration.IsTypeOnly && exportDeclaration.ModuleSpecifier == nil && !ast.IsStringLiteral(name) { + 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) @@ -2755,7 +2755,7 @@ func (c *Checker) extendAssignmentPosition(node *ast.Node, declaration *ast.Node ast.KindTryStatement, ast.KindClassDeclaration: pos = node.End() } - node = node.Parent + node = node.Parent() } return pos } diff --git a/tsc/internal/checker/grammarchecks.go b/tsc/internal/checker/grammarchecks.go index 5fb15267933c8..e7b7b192f265f 100644 --- a/tsc/internal/checker/grammarchecks.go +++ b/tsc/internal/checker/grammarchecks.go @@ -103,12 +103,12 @@ func (c *Checker) checkGrammarPrivateIdentifierExpression(privId *ast.PrivateIde return c.grammarErrorOnNode(privId.AsNode(), diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies) } - if !ast.IsForInStatement(privId.Parent) { + if !ast.IsForInStatement(privId.Parent()) { if !ast.IsExpressionNode(privIdAsNode) { return c.grammarErrorOnNode(privIdAsNode, diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression) } - isInOperation := ast.IsBinaryExpression(privId.Parent) && privId.Parent.AsBinaryExpression().OperatorToken.Kind == ast.KindInKeyword + isInOperation := ast.IsBinaryExpression(privId.Parent()) && privId.Parent().AsBinaryExpression().OperatorToken().Kind == ast.KindInKeyword if c.getSymbolForPrivateIdentifierExpression(privIdAsNode) == nil && !isInOperation { return c.grammarErrorOnNode(privIdAsNode, diagnostics.Cannot_find_name_0, privId.Text) } @@ -118,8 +118,8 @@ func (c *Checker) checkGrammarPrivateIdentifierExpression(privId *ast.PrivateIde } func (c *Checker) checkGrammarMappedType(node *ast.MappedTypeNode) bool { - if len(node.Members.Nodes) > 0 { - return c.grammarErrorOnNode(node.Members.Nodes[0], diagnostics.A_mapped_type_may_not_declare_properties_or_methods) + if len(node.Members().Nodes) > 0 { + return c.grammarErrorOnNode(node.Members().Nodes[0], diagnostics.A_mapped_type_may_not_declare_properties_or_methods) } return false } @@ -127,7 +127,7 @@ func (c *Checker) checkGrammarMappedType(node *ast.MappedTypeNode) bool { func (c *Checker) checkGrammarDecorator(decorator *ast.Decorator) bool { sourceFile := ast.GetSourceFileOfNode(decorator.AsNode()) if !c.hasParseDiagnostics(sourceFile) { - node := decorator.Expression + node := decorator.Expression() // DecoratorParenthesizedExpression : // `(` Expression `)` @@ -153,11 +153,11 @@ func (c *Checker) checkGrammarDecorator(decorator *ast.Decorator) bool { if !canHaveCallExpression { errorNode = node } - if callExpr.QuestionDotToken != nil { + if callExpr.QuestionDotToken() != nil { // Even if we already have an error node, error at the `?.` token since it appears earlier. - errorNode = callExpr.QuestionDotToken + errorNode = callExpr.QuestionDotToken() } - node = callExpr.Expression + node = callExpr.Expression() canHaveCallExpression = false continue } @@ -169,11 +169,11 @@ func (c *Checker) checkGrammarDecorator(decorator *ast.Decorator) bool { if ast.IsPropertyAccessExpression(node) { propertyAccessExpr := node.AsPropertyAccessExpression() - if propertyAccessExpr.QuestionDotToken != nil { + if propertyAccessExpr.QuestionDotToken() != nil { // Even if we already have an error node, error at the `?.` token since it appears earlier. - errorNode = propertyAccessExpr.QuestionDotToken + errorNode = propertyAccessExpr.QuestionDotToken() } - node = propertyAccessExpr.Expression + node = propertyAccessExpr.Expression() canHaveCallExpression = false continue } @@ -187,7 +187,7 @@ func (c *Checker) checkGrammarDecorator(decorator *ast.Decorator) bool { } if errorNode != nil { - err := c.error(decorator.Expression, diagnostics.Expression_must_be_enclosed_in_parentheses_to_be_used_as_a_decorator) + err := c.error(decorator.Expression(), diagnostics.Expression_must_be_enclosed_in_parentheses_to_be_used_as_a_decorator) err.AddRelatedInfo(createDiagnosticForNode(errorNode, diagnostics.Invalid_syntax_in_decorator)) return true } @@ -197,14 +197,14 @@ func (c *Checker) checkGrammarDecorator(decorator *ast.Decorator) bool { } func (c *Checker) checkGrammarExportDeclaration(node *ast.ExportDeclaration) bool { - if node.IsTypeOnly && node.ExportClause != nil && node.ExportClause.Kind == ast.KindNamedExports { - return c.checkGrammarTypeOnlyNamedImportsOrExports(node.ExportClause) + if node.IsTypeOnly && node.ExportClause() != nil && node.ExportClause().Kind == ast.KindNamedExports { + return c.checkGrammarTypeOnlyNamedImportsOrExports(node.ExportClause()) } return false } func (c *Checker) checkGrammarModuleElementContext(node *ast.Statement, errorMessage *diagnostics.Message) bool { - isInAppropriateContext := node.Parent.Kind == ast.KindSourceFile || node.Parent.Kind == ast.KindModuleBlock || node.Parent.Kind == ast.KindModuleDeclaration + isInAppropriateContext := node.Parent().Kind == ast.KindSourceFile || node.Parent().Kind == ast.KindModuleBlock || node.Parent().Kind == ast.KindModuleDeclaration if !isInAppropriateContext { c.grammarErrorOnFirstToken(node, errorMessage) } @@ -223,7 +223,7 @@ func (c *Checker) checkGrammarModifiers(node *ast.Node /*Union[HasModifiers, Has } blockScopeKind := ast.NodeFlagsNone if ast.IsVariableStatement(node) { - blockScopeKind = node.AsVariableStatement().DeclarationList.Flags & ast.NodeFlagsBlockScoped + blockScopeKind = node.AsVariableStatement().DeclarationList().Flags & ast.NodeFlagsBlockScoped } var lastStatic *ast.Node var lastDeclare *ast.Node @@ -239,7 +239,7 @@ func (c *Checker) checkGrammarModifiers(node *ast.Node /*Union[HasModifiers, Has modifiers := node.ModifierNodes() for _, modifier := range modifiers { if ast.IsDecorator(modifier) { - if !ast.NodeCanBeDecorated(c.legacyDecorators, node, node.Parent, node.Parent.Parent) { + if !ast.NodeCanBeDecorated(c.legacyDecorators, node, node.Parent(), node.Parent().Parent()) { if node.Kind == ast.KindMethodDeclaration && !ast.NodeIsPresent(node.Body()) { return c.grammarErrorOnFirstToken(node, diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload) } else { @@ -288,7 +288,7 @@ func (c *Checker) checkGrammarModifiers(node *ast.Node /*Union[HasModifiers, Has if node.Kind == ast.KindPropertySignature || node.Kind == ast.KindMethodSignature { return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_cannot_appear_on_a_type_member, scanner.TokenToString(modifier.Kind)) } - if node.Kind == ast.KindIndexSignature && (modifier.Kind != ast.KindStaticKeyword || !ast.IsClassLike(node.Parent)) { + if node.Kind == ast.KindIndexSignature && (modifier.Kind != ast.KindStaticKeyword || !ast.IsClassLike(node.Parent())) { return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_cannot_appear_on_an_index_signature, scanner.TokenToString(modifier.Kind)) } } @@ -302,7 +302,7 @@ func (c *Checker) checkGrammarModifiers(node *ast.Node /*Union[HasModifiers, Has if node.Kind != ast.KindEnumDeclaration && node.Kind != ast.KindTypeParameter { return c.grammarErrorOnNode(node, diagnostics.A_class_member_cannot_have_the_0_keyword, scanner.TokenToString(ast.KindConstKeyword)) } - parent := node.Parent + parent := node.Parent() if node.Kind == ast.KindTypeParameter { if !(ast.IsFunctionLikeDeclaration(parent) || ast.IsClassLike(parent) || ast.IsFunctionTypeNode(parent) || ast.IsConstructorTypeNode(parent) || @@ -344,7 +344,7 @@ func (c *Checker) checkGrammarModifiers(node *ast.Node /*Union[HasModifiers, Has return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_must_precede_1_modifier, text, "readonly") } else if flags&ast.ModifierFlagsAsync != 0 && modifier.Flags&ast.NodeFlagsReparsed == 0 { return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_must_precede_1_modifier, text, "async") - } else if node.Parent.Kind == ast.KindModuleBlock || node.Parent.Kind == ast.KindSourceFile { + } else if node.Parent().Kind == ast.KindModuleBlock || node.Parent().Kind == ast.KindSourceFile { return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_cannot_appear_on_a_module_or_namespace_element, text) } else if flags&ast.ModifierFlagsAbstract != 0 { if modifier.Kind == ast.KindPrivateKeyword { @@ -365,7 +365,7 @@ func (c *Checker) checkGrammarModifiers(node *ast.Node /*Union[HasModifiers, Has return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_must_precede_1_modifier, "static", "async") } else if flags&ast.ModifierFlagsAccessor != 0 && modifier.Flags&ast.NodeFlagsReparsed == 0 { return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_must_precede_1_modifier, "static", "accessor") - } else if node.Parent.Kind == ast.KindModuleBlock || node.Parent.Kind == ast.KindSourceFile { + } else if node.Parent().Kind == ast.KindModuleBlock || node.Parent().Kind == ast.KindSourceFile { return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_cannot_appear_on_a_module_or_namespace_element, "static") } else if node.Kind == ast.KindParameter { return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_cannot_appear_on_a_parameter, "static") @@ -399,7 +399,7 @@ func (c *Checker) checkGrammarModifiers(node *ast.Node /*Union[HasModifiers, Has } flags |= ast.ModifierFlagsReadonly case ast.KindExportKeyword: - if c.compilerOptions.VerbatimModuleSyntax == core.TSTrue && node.Flags&ast.NodeFlagsAmbient == 0 && node.Kind != ast.KindTypeAliasDeclaration && node.Kind != ast.KindInterfaceDeclaration && node.Kind != ast.KindModuleDeclaration && node.Parent.Kind == ast.KindSourceFile && c.program.GetEmitModuleFormatOfFile(ast.GetSourceFileOfNode(node)) == core.ModuleKindCommonJS { + if c.compilerOptions.VerbatimModuleSyntax == core.TSTrue && node.Flags&ast.NodeFlagsAmbient == 0 && node.Kind != ast.KindTypeAliasDeclaration && node.Kind != ast.KindInterfaceDeclaration && node.Kind != ast.KindModuleDeclaration && node.Parent().Kind == ast.KindSourceFile && c.program.GetEmitModuleFormatOfFile(ast.GetSourceFileOfNode(node)) == core.ModuleKindCommonJS { return c.grammarErrorOnNode(modifier, diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled) } if flags&ast.ModifierFlagsExport != 0 { @@ -410,7 +410,7 @@ func (c *Checker) checkGrammarModifiers(node *ast.Node /*Union[HasModifiers, Has return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_must_precede_1_modifier, "export", "abstract") } else if flags&ast.ModifierFlagsAsync != 0 && modifier.Flags&ast.NodeFlagsReparsed == 0 { return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_must_precede_1_modifier, "export", "async") - } else if ast.IsClassLike(node.Parent) && !ast.IsJSTypeAliasDeclaration(node) { + } else if ast.IsClassLike(node.Parent()) && !ast.IsJSTypeAliasDeclaration(node) { return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_cannot_appear_on_class_elements_of_this_kind, "export") } else if node.Kind == ast.KindParameter { return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_cannot_appear_on_a_parameter, "export") @@ -422,10 +422,10 @@ func (c *Checker) checkGrammarModifiers(node *ast.Node /*Union[HasModifiers, Has flags |= ast.ModifierFlagsExport case ast.KindDefaultKeyword: var container *ast.Node - if node.Parent.Kind == ast.KindSourceFile { - container = node.Parent + if node.Parent().Kind == ast.KindSourceFile { + container = node.Parent() } else { - container = node.Parent.Parent + container = node.Parent().Parent() } if container.Kind == ast.KindModuleDeclaration && !ast.IsAmbientModule(container) { return c.grammarErrorOnNode(modifier, diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module) @@ -447,7 +447,7 @@ func (c *Checker) checkGrammarModifiers(node *ast.Node /*Union[HasModifiers, Has return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_cannot_be_used_in_an_ambient_context, "async") } else if flags&ast.ModifierFlagsOverride != 0 { return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_cannot_be_used_in_an_ambient_context, "override") - } else if ast.IsClassLike(node.Parent) && !ast.IsPropertyDeclaration(node) { + } else if ast.IsClassLike(node.Parent()) && !ast.IsPropertyDeclaration(node) { return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_cannot_appear_on_class_elements_of_this_kind, "declare") } else if node.Kind == ast.KindParameter { return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_cannot_appear_on_a_parameter, "declare") @@ -455,7 +455,7 @@ func (c *Checker) checkGrammarModifiers(node *ast.Node /*Union[HasModifiers, Has return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_cannot_appear_on_a_using_declaration, "declare") } else if blockScopeKind == ast.NodeFlagsAwaitUsing { return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_cannot_appear_on_an_await_using_declaration, "declare") - } else if (node.Parent.Flags&ast.NodeFlagsAmbient != 0) && node.Parent.Kind == ast.KindModuleBlock { + } else if (node.Parent().Flags&ast.NodeFlagsAmbient != 0) && node.Parent().Kind == ast.KindModuleBlock { return c.grammarErrorOnNode(modifier, diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context) } else if ast.IsPrivateIdentifierClassElementDeclaration(node) { return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_cannot_be_used_with_a_private_identifier, "declare") @@ -472,7 +472,7 @@ func (c *Checker) checkGrammarModifiers(node *ast.Node /*Union[HasModifiers, Has if node.Kind != ast.KindMethodDeclaration && node.Kind != ast.KindPropertyDeclaration && node.Kind != ast.KindGetAccessor && node.Kind != ast.KindSetAccessor { return c.grammarErrorOnNode(modifier, diagnostics.X_abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration) } - if !(node.Parent.Kind == ast.KindClassDeclaration && ast.HasSyntacticModifier(node.Parent, ast.ModifierFlagsAbstract)) { + if !(node.Parent().Kind == ast.KindClassDeclaration && ast.HasSyntacticModifier(node.Parent(), ast.ModifierFlagsAbstract)) { var message *diagnostics.Message if node.Kind == ast.KindPropertyDeclaration { message = diagnostics.Abstract_properties_can_only_appear_within_an_abstract_class @@ -505,7 +505,7 @@ func (c *Checker) checkGrammarModifiers(node *ast.Node /*Union[HasModifiers, Has case ast.KindAsyncKeyword: if flags&ast.ModifierFlagsAsync != 0 { return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_already_seen, "async") - } else if flags&ast.ModifierFlagsAmbient != 0 || node.Parent.Flags&ast.NodeFlagsAmbient != 0 { + } else if flags&ast.ModifierFlagsAmbient != 0 || node.Parent().Flags&ast.NodeFlagsAmbient != 0 { return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_cannot_be_used_in_an_ambient_context, "async") } else if node.Kind == ast.KindParameter { return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_cannot_appear_on_a_parameter, "async") @@ -529,7 +529,7 @@ func (c *Checker) checkGrammarModifiers(node *ast.Node /*Union[HasModifiers, Has } else { inOutText = "out" } - parent := node.Parent + parent := node.Parent() if node.Kind != ast.KindTypeParameter || parent != nil && !(ast.IsInterfaceDeclaration(parent) || ast.IsClassLike(parent) || ast.IsTypeOrJSTypeAliasDeclaration(parent)) { return c.grammarErrorOnNode(modifier, diagnostics.X_0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias, inOutText) } @@ -559,7 +559,7 @@ func (c *Checker) checkGrammarModifiers(node *ast.Node /*Union[HasModifiers, Has return c.grammarErrorOnNode(lastDeclare, diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare") } else if node.Kind == ast.KindParameter && (flags&ast.ModifierFlagsParameterPropertyModifier != 0) && ast.IsBindingPattern(node.Name()) { return c.grammarErrorOnNode(node, diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern) - } else if node.Kind == ast.KindParameter && (flags&ast.ModifierFlagsParameterPropertyModifier != 0) && node.AsParameterDeclaration().DotDotDotToken != nil { + } else if node.Kind == ast.KindParameter && (flags&ast.ModifierFlagsParameterPropertyModifier != 0) && node.AsParameterDeclaration().DotDotDotToken() != nil { return c.grammarErrorOnNode(node, diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter) } if flags&ast.ModifierFlagsAsync != 0 { @@ -613,7 +613,7 @@ func (c *Checker) findFirstIllegalModifier(node *ast.Node) *ast.Node { ast.KindMissingDeclaration: return core.Find(node.ModifierNodes(), ast.IsModifier) default: - if node.Parent.Kind == ast.KindModuleBlock || node.Parent.Kind == ast.KindSourceFile { + if node.Parent().Kind == ast.KindModuleBlock || node.Parent().Kind == ast.KindSourceFile { return nil } switch node.Kind { @@ -627,7 +627,7 @@ func (c *Checker) findFirstIllegalModifier(node *ast.Node) *ast.Node { ast.KindTypeAliasDeclaration: return core.Find(node.ModifierNodes(), ast.IsModifier) case ast.KindVariableStatement: - if node.AsVariableStatement().DeclarationList.Flags&ast.NodeFlagsUsing != 0 { + if node.AsVariableStatement().DeclarationList().Flags&ast.NodeFlagsUsing != 0 { return c.findFirstModifierExcept(node, ast.KindAwaitKeyword) } return core.Find(node.ModifierNodes(), ast.IsModifier) @@ -690,28 +690,28 @@ func (c *Checker) checkGrammarParameterList(parameters *ast.NodeList) bool { for i := range parameterCount { parameter := parameters.Nodes[i].AsParameterDeclaration() - if parameter.DotDotDotToken != nil { + if parameter.DotDotDotToken() != nil { if i != parameterCount-1 { - return c.grammarErrorOnNode(parameter.DotDotDotToken, diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list) + return c.grammarErrorOnNode(parameter.DotDotDotToken(), diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list) } if parameter.Flags&ast.NodeFlagsAmbient == 0 { c.checkGrammarForDisallowedTrailingComma(parameters, diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma) } - if parameter.QuestionToken != nil { - return c.grammarErrorOnNode(parameter.QuestionToken, diagnostics.A_rest_parameter_cannot_be_optional) + if parameter.QuestionToken() != nil { + return c.grammarErrorOnNode(parameter.QuestionToken(), diagnostics.A_rest_parameter_cannot_be_optional) } - if parameter.Initializer != nil { + if parameter.Initializer() != nil { return c.grammarErrorOnNode(parameter.Name(), diagnostics.A_rest_parameter_cannot_have_an_initializer) } } else if isOptionalDeclaration(parameter.AsNode()) { seenOptionalParameter = true // A reparsed '?' token indicates a bracketed name in @param tag - if parameter.QuestionToken != nil && parameter.QuestionToken.Flags&ast.NodeFlagsReparsed == 0 && parameter.Initializer != nil { + if parameter.QuestionToken() != nil && parameter.QuestionToken().Flags&ast.NodeFlagsReparsed == 0 && parameter.Initializer() != nil { return c.grammarErrorOnNode(parameter.Name(), diagnostics.Parameter_cannot_have_question_mark_and_initializer) } - } else if seenOptionalParameter && parameter.Initializer == nil { + } else if seenOptionalParameter && parameter.Initializer() == nil { return c.grammarErrorOnNode(parameter.Name(), diagnostics.A_required_parameter_cannot_follow_an_optional_parameter) } } @@ -729,7 +729,7 @@ func (c *Checker) checkGrammarForUseStrictSimpleParameterList(node *ast.Node) bo if useStrictDirective != nil { nonSimpleParameters := core.Filter(node.Parameters(), func(n *ast.Node) bool { parameter := n.AsParameterDeclaration() - return parameter.Initializer != nil || ast.IsBindingPattern(parameter.Name()) || isRestParameter(parameter.AsNode()) + return parameter.Initializer() != nil || ast.IsBindingPattern(parameter.Name()) || isRestParameter(parameter.AsNode()) }) if len(nonSimpleParameters) != 0 { for _, parameter := range nonSimpleParameters { @@ -759,8 +759,8 @@ func (c *Checker) checkGrammarFunctionLikeDeclaration(node *ast.Node) bool { // Prevent cascading error by short-circuit file := ast.GetSourceFileOfNode(node) funcData := node.FunctionLikeData() - return c.checkGrammarModifiers(node) || c.checkGrammarTypeParameterList(funcData.TypeParameters, file) || - c.checkGrammarParameterList(funcData.Parameters) || c.checkGrammarArrowFunction(node, file) || + return c.checkGrammarModifiers(node) || c.checkGrammarTypeParameterList(funcData.TypeParameters(), file) || + c.checkGrammarParameterList(funcData.Parameters()) || c.checkGrammarArrowFunction(node, file) || (ast.IsFunctionLikeDeclaration(node) && c.checkGrammarForUseStrictSimpleParameterList(node)) } @@ -775,10 +775,10 @@ func (c *Checker) checkGrammarArrowFunction(node *ast.Node, file *ast.SourceFile } arrowFunc := node.AsArrowFunction() - typeParameters := arrowFunc.TypeParameters + typeParameters := arrowFunc.TypeParameters() if typeParameters != nil { typeParamNodes := typeParameters.Nodes - hasConstraint := len(typeParamNodes) > 0 && typeParamNodes[0].AsTypeParameterDeclaration().Constraint != nil + hasConstraint := len(typeParamNodes) > 0 && typeParamNodes[0].AsTypeParameterDeclaration().Constraint() != nil if !(len(typeParamNodes) > 1 || typeParameters.HasTrailingComma() || hasConstraint) { if file.FileName().ExtensionIsOneOf([]string{tspath.ExtensionMts, tspath.ExtensionCts}) { // TODO(danielr): should we return early here? @@ -787,14 +787,14 @@ func (c *Checker) checkGrammarArrowFunction(node *ast.Node, file *ast.SourceFile } } - equalsGreaterThanToken := arrowFunc.EqualsGreaterThanToken + equalsGreaterThanToken := arrowFunc.EqualsGreaterThanToken() arrowFullText := file.Text()[equalsGreaterThanToken.Pos():equalsGreaterThanToken.End()] return strings.ContainsFunc(arrowFullText, stringutil.IsLineBreak) && c.grammarErrorOnNode(equalsGreaterThanToken, diagnostics.Line_terminator_not_permitted_before_arrow) } func (c *Checker) checkGrammarIndexSignatureParameters(node *ast.IndexSignatureDeclaration) bool { - paramNodes := node.Parameters.Nodes + paramNodes := node.Parameters().Nodes if len(paramNodes) == 0 { return c.grammarErrorOnNode(node.AsNode(), diagnostics.An_index_signature_must_have_exactly_one_parameter) @@ -805,20 +805,20 @@ func (c *Checker) checkGrammarIndexSignatureParameters(node *ast.IndexSignatureD return c.grammarErrorOnNode(parameter.Name(), diagnostics.An_index_signature_must_have_exactly_one_parameter) } - c.checkGrammarForDisallowedTrailingComma(node.Parameters, diagnostics.An_index_signature_cannot_have_a_trailing_comma) - if parameter.DotDotDotToken != nil { - return c.grammarErrorOnNode(parameter.DotDotDotToken, diagnostics.An_index_signature_cannot_have_a_rest_parameter) + c.checkGrammarForDisallowedTrailingComma(node.Parameters(), diagnostics.An_index_signature_cannot_have_a_trailing_comma) + if parameter.DotDotDotToken() != nil { + return c.grammarErrorOnNode(parameter.DotDotDotToken(), diagnostics.An_index_signature_cannot_have_a_rest_parameter) } if parameter.Modifiers() != nil { return c.grammarErrorOnNode(parameter.Name(), diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier) } - if parameter.QuestionToken != nil { - return c.grammarErrorOnNode(parameter.QuestionToken, diagnostics.An_index_signature_parameter_cannot_have_a_question_mark) + if parameter.QuestionToken() != nil { + return c.grammarErrorOnNode(parameter.QuestionToken(), diagnostics.An_index_signature_parameter_cannot_have_a_question_mark) } - if parameter.Initializer != nil { + if parameter.Initializer() != nil { return c.grammarErrorOnNode(parameter.Name(), diagnostics.An_index_signature_parameter_cannot_have_an_initializer) } - typeNode := parameter.Type + typeNode := parameter.Type() if typeNode == nil { return c.grammarErrorOnNode(parameter.Name(), diagnostics.An_index_signature_parameter_must_have_a_type_annotation) } @@ -831,7 +831,7 @@ func (c *Checker) checkGrammarIndexSignatureParameters(node *ast.IndexSignatureD if !everyType(t, c.isValidIndexKeyType) { return c.grammarErrorOnNode(parameter.Name(), diagnostics.An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type) } - if node.Type == nil { + if node.Type() == nil { return c.grammarErrorOnNode(node.AsNode(), diagnostics.An_index_signature_must_have_a_type_annotation) } return false @@ -857,14 +857,14 @@ func (c *Checker) checkGrammarTypeArguments(node *ast.Node, typeArguments *ast.N } func (c *Checker) checkGrammarTaggedTemplateChain(node *ast.TaggedTemplateExpression) bool { - if node.QuestionDotToken != nil || node.Flags&ast.NodeFlagsOptionalChain != 0 { - return c.grammarErrorOnNode(node.Template, diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain) + if node.QuestionDotToken() != nil || node.Flags&ast.NodeFlagsOptionalChain != 0 { + return c.grammarErrorOnNode(node.Template(), diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain) } return false } func (c *Checker) checkGrammarHeritageClause(node *ast.HeritageClause) bool { - types := node.Types + types := node.Types() if c.checkGrammarForDisallowedTrailingComma(types, diagnostics.Trailing_comma_not_allowed) { return true } @@ -895,8 +895,8 @@ func (c *Checker) checkGrammarClassDeclarationHeritageClauses(node *ast.ClassLik classLikeData := node.ClassLikeData() - if !c.checkGrammarModifiers(node) && classLikeData.HeritageClauses != nil { - for _, heritageClauseNode := range classLikeData.HeritageClauses.Nodes { + if !c.checkGrammarModifiers(node) && classLikeData.HeritageClauses() != nil { + for _, heritageClauseNode := range classLikeData.HeritageClauses().Nodes { heritageClause := heritageClauseNode.AsHeritageClause() if heritageClause.Token == ast.KindExtendsKeyword { if seenExtendsClause { @@ -907,7 +907,7 @@ func (c *Checker) checkGrammarClassDeclarationHeritageClauses(node *ast.ClassLik return c.grammarErrorOnFirstToken(heritageClauseNode, diagnostics.X_extends_clause_must_precede_implements_clause) } - typeNodes := heritageClause.Types.Nodes + typeNodes := heritageClause.Types().Nodes if len(typeNodes) > 1 { return c.grammarErrorOnFirstToken(typeNodes[1], diagnostics.Classes_can_only_extend_a_single_class) } @@ -933,9 +933,9 @@ func (c *Checker) checkGrammarClassDeclarationHeritageClauses(node *ast.ClassLik } func (c *Checker) checkGrammarInterfaceDeclaration(node *ast.InterfaceDeclaration) bool { - if node.HeritageClauses != nil { + if node.HeritageClauses() != nil { seenExtendsClause := false - for _, heritageClauseNode := range node.HeritageClauses.Nodes { + for _, heritageClauseNode := range node.HeritageClauses().Nodes { heritageClause := heritageClauseNode.AsHeritageClause() switch heritageClause.Token { @@ -965,22 +965,22 @@ func (c *Checker) checkGrammarComputedPropertyName(node *ast.Node) bool { } computedPropertyName := node.AsComputedPropertyName() - if computedPropertyName.Expression.Kind == ast.KindBinaryExpression && computedPropertyName.Expression.AsBinaryExpression().OperatorToken.Kind == ast.KindCommaToken { - return c.grammarErrorOnNode(computedPropertyName.Expression, diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name) + if computedPropertyName.Expression().Kind == ast.KindBinaryExpression && computedPropertyName.Expression().AsBinaryExpression().OperatorToken().Kind == ast.KindCommaToken { + return c.grammarErrorOnNode(computedPropertyName.Expression(), diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name) } return false } func (c *Checker) checkGrammarForGenerator(node *ast.Node) bool { - if bodyData := node.BodyData(); bodyData != nil && bodyData.AsteriskToken != nil { + if bodyData := node.BodyData(); bodyData != nil && bodyData.AsteriskToken() != nil { if node.Kind != ast.KindFunctionDeclaration && node.Kind != ast.KindFunctionExpression && node.Kind != ast.KindMethodDeclaration { panic(fmt.Sprintf("Unexpected node kind %q", node.Kind)) } if node.Flags&ast.NodeFlagsAmbient != 0 { - return c.grammarErrorOnNode(bodyData.AsteriskToken, diagnostics.Generators_are_not_allowed_in_an_ambient_context) + return c.grammarErrorOnNode(bodyData.AsteriskToken(), diagnostics.Generators_are_not_allowed_in_an_ambient_context) } - if bodyData.Body == nil { - return c.grammarErrorOnNode(bodyData.AsteriskToken, diagnostics.An_overload_signature_cannot_be_declared_as_a_generator) + if bodyData.Body() == nil { + return c.grammarErrorOnNode(bodyData.AsteriskToken(), diagnostics.An_overload_signature_cannot_be_declared_as_a_generator) } } @@ -999,17 +999,17 @@ func (c *Checker) checkGrammarObjectLiteralExpression(node *ast.ObjectLiteralExp seen := make(map[string]DeclarationMeaning) var properties []*ast.Node - if node.Properties != nil { - properties = node.Properties.Nodes + if node.Properties() != nil { + properties = node.Properties().Nodes } for _, prop := range properties { if prop.Kind == ast.KindSpreadAssignment { spreadAssignment := prop.AsSpreadAssignment() if inDestructuring { // a rest property cannot be destructured any further - expression := ast.SkipParentheses(spreadAssignment.Expression) + expression := ast.SkipParentheses(spreadAssignment.Expression()) if ast.IsArrayLiteralExpression(expression) || ast.IsObjectLiteralExpression(expression) { - return c.grammarErrorOnNode(spreadAssignment.Expression, diagnostics.A_rest_element_cannot_contain_a_binding_pattern) + return c.grammarErrorOnNode(spreadAssignment.Expression(), diagnostics.A_rest_element_cannot_contain_a_binding_pattern) } } continue @@ -1022,7 +1022,7 @@ func (c *Checker) checkGrammarObjectLiteralExpression(node *ast.ObjectLiteralExp if prop.Kind == ast.KindShorthandPropertyAssignment && !inDestructuring { shorthandProp := prop.AsShorthandPropertyAssignment() - if shorthandProp.ObjectAssignmentInitializer != nil { + if shorthandProp.ObjectAssignmentInitializer() != nil { // having objectAssignmentInitializer is only valid in an ObjectAssignmentPattern. // Outside of destructuring, it is a syntax error. @@ -1030,7 +1030,7 @@ func (c *Checker) checkGrammarObjectLiteralExpression(node *ast.ObjectLiteralExp // then error on the first token following (which should be the `=` token). var lastNodeBeforeInitializer *ast.Node shorthandProp.ForEachChild(func(child *ast.Node) bool { - if child != shorthandProp.ObjectAssignmentInitializer { + if child != shorthandProp.ObjectAssignmentInitializer() { lastNodeBeforeInitializer = child return false } @@ -1083,8 +1083,8 @@ func (c *Checker) checkGrammarObjectLiteralExpression(node *ast.ObjectLiteralExp } // Grammar checking for computedPropertyName and shorthandPropertyAssignment - c.checkGrammarForInvalidExclamationToken(commonProp.PostfixToken, diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context) - c.checkGrammarForInvalidQuestionMark(commonProp.PostfixToken, diagnostics.An_object_member_cannot_be_declared_optional) + c.checkGrammarForInvalidExclamationToken(commonProp.PostfixToken(), diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context) + c.checkGrammarForInvalidQuestionMark(commonProp.PostfixToken(), diagnostics.An_object_member_cannot_be_declared_optional) if name.Kind == ast.KindNumericLiteral { c.checkGrammarNumericLiteral(name.AsNumericLiteral()) @@ -1145,7 +1145,7 @@ func (c *Checker) checkGrammarJsxElement(node *ast.Node) bool { } attr := attrNode.AsJsxAttribute() name := attr.Name() - initializer := attr.Initializer + initializer := attr.Initializer() textOfName := name.Text() if !seen.Has(textOfName) { seen.Add(textOfName) @@ -1164,7 +1164,7 @@ func (c *Checker) checkGrammarJsxName(node *ast.JsxTagNameExpression) bool { return c.grammarErrorOnNode(node.Expression(), diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names) } - if ast.IsJsxNamespacedName(node) && c.compilerOptions.GetJSXTransformEnabled() && !scanner.IsIntrinsicJsxName(node.AsJsxNamespacedName().Namespace.Text()) { + if ast.IsJsxNamespacedName(node) && c.compilerOptions.GetJSXTransformEnabled() && !scanner.IsIntrinsicJsxName(node.AsJsxNamespacedName().Namespace().Text()) { return c.grammarErrorOnNode(node, diagnostics.React_components_cannot_include_JSX_namespace_names) } @@ -1172,8 +1172,8 @@ func (c *Checker) checkGrammarJsxName(node *ast.JsxTagNameExpression) bool { } func (c *Checker) checkGrammarJsxExpression(node *ast.JsxExpression) bool { - if node.Expression != nil && ast.IsCommaSequence(node.Expression) { - return c.grammarErrorOnNode(node.Expression, diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array) + if node.Expression() != nil && ast.IsCommaSequence(node.Expression()) { + return c.grammarErrorOnNode(node.Expression(), diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array) } return false @@ -1185,19 +1185,19 @@ func (c *Checker) checkGrammarForInOrForOfStatement(forInOrOfStatement *ast.ForI return true } - if forInOrOfStatement.Kind == ast.KindForOfStatement && forInOrOfStatement.AwaitModifier != nil { + if forInOrOfStatement.Kind == ast.KindForOfStatement && forInOrOfStatement.AwaitModifier() != nil { if forInOrOfStatement.Flags&ast.NodeFlagsAwaitContext == 0 { sourceFile := ast.GetSourceFileOfNode(asNode) if ast.IsInTopLevelContext(asNode) { if !c.hasParseDiagnostics(sourceFile) { if !ast.IsEffectiveExternalModule(sourceFile, c.compilerOptions) { - c.addDiagnostic(createDiagnosticForNode(forInOrOfStatement.AwaitModifier, diagnostics.X_for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module)) + c.addDiagnostic(createDiagnosticForNode(forInOrOfStatement.AwaitModifier(), diagnostics.X_for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module)) } switch c.moduleKind { case core.ModuleKindNode16, core.ModuleKindNode18, core.ModuleKindNode20, core.ModuleKindNodeNext: sourceFileMetaData := c.program.GetSourceFileMetaData(sourceFile.PathKey()) if sourceFileMetaData.ImpliedNodeFormat == core.ModuleKindCommonJS { - c.addDiagnostic(createDiagnosticForNode(forInOrOfStatement.AwaitModifier, diagnostics.The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level)) + c.addDiagnostic(createDiagnosticForNode(forInOrOfStatement.AwaitModifier(), diagnostics.The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level)) break } fallthrough @@ -1210,13 +1210,13 @@ func (c *Checker) checkGrammarForInOrForOfStatement(forInOrOfStatement *ast.ForI } fallthrough default: - c.addDiagnostic(createDiagnosticForNode(forInOrOfStatement.AwaitModifier, diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_node18_node20_nodenext_or_preserve_and_the_target_option_is_set_to_es2017_or_higher)) + c.addDiagnostic(createDiagnosticForNode(forInOrOfStatement.AwaitModifier(), diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_node18_node20_nodenext_or_preserve_and_the_target_option_is_set_to_es2017_or_higher)) } } } else { // use of 'for-await-of' in non-async function if !c.hasParseDiagnostics(sourceFile) { - diagnostic := createDiagnosticForNode(forInOrOfStatement.AwaitModifier, diagnostics.X_for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules) + diagnostic := createDiagnosticForNode(forInOrOfStatement.AwaitModifier(), diagnostics.X_for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules) containingFunc := ast.GetContainingFunction(forInOrOfStatement.AsNode()) if containingFunc != nil && containingFunc.Kind != ast.KindConstructor { debug.Assert((ast.GetFunctionFlags(containingFunc)&ast.FunctionFlagsAsync) == 0, "Enclosing function should never be an async function.") @@ -1230,15 +1230,15 @@ func (c *Checker) checkGrammarForInOrForOfStatement(forInOrOfStatement *ast.ForI } } - if ast.IsForOfStatement(asNode) && forInOrOfStatement.Flags&ast.NodeFlagsAwaitContext == 0 && ast.IsIdentifier(forInOrOfStatement.Initializer) && forInOrOfStatement.Initializer.Text() == "async" { - c.grammarErrorOnNode(forInOrOfStatement.Initializer, diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_async) + if ast.IsForOfStatement(asNode) && forInOrOfStatement.Flags&ast.NodeFlagsAwaitContext == 0 && ast.IsIdentifier(forInOrOfStatement.Initializer()) && forInOrOfStatement.Initializer().Text() == "async" { + c.grammarErrorOnNode(forInOrOfStatement.Initializer(), diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_async) return false } - if forInOrOfStatement.Initializer.Kind == ast.KindVariableDeclarationList { - variableList := forInOrOfStatement.Initializer.AsVariableDeclarationList() + if forInOrOfStatement.Initializer().Kind == ast.KindVariableDeclarationList { + variableList := forInOrOfStatement.Initializer().AsVariableDeclarationList() if !c.checkGrammarVariableDeclarationList(variableList) { - declarations := variableList.Declarations + declarations := variableList.Declarations() // declarations.length can be zero if there is an error in variable declaration in for-of or for-in // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details @@ -1262,7 +1262,7 @@ func (c *Checker) checkGrammarForInOrForOfStatement(forInOrOfStatement *ast.ForI } firstVariableDeclaration := declarations.Nodes[0].AsVariableDeclaration() - if firstVariableDeclaration.Initializer != nil { + if firstVariableDeclaration.Initializer() != nil { var diagnostic *diagnostics.Message if forInOrOfStatement.Kind == ast.KindForInStatement { diagnostic = diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer @@ -1271,7 +1271,7 @@ func (c *Checker) checkGrammarForInOrForOfStatement(forInOrOfStatement *ast.ForI } return c.grammarErrorOnNode(firstVariableDeclaration.Name(), diagnostic) } - if firstVariableDeclaration.Type != nil { + if firstVariableDeclaration.Type() != nil { var diagnostic *diagnostics.Message if forInOrOfStatement.Kind == ast.KindForInStatement { diagnostic = diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation @@ -1288,7 +1288,7 @@ func (c *Checker) checkGrammarForInOrForOfStatement(forInOrOfStatement *ast.ForI func (c *Checker) checkGrammarAccessor(accessor *ast.AccessorDeclaration) bool { body := accessor.Body() - if accessor.Flags&ast.NodeFlagsAmbient == 0 && (accessor.Parent.Kind != ast.KindTypeLiteral) && (accessor.Parent.Kind != ast.KindInterfaceDeclaration) { + if accessor.Flags&ast.NodeFlagsAmbient == 0 && (accessor.Parent().Kind != ast.KindTypeLiteral) && (accessor.Parent().Kind != ast.KindInterfaceDeclaration) { if body == nil && !ast.HasSyntacticModifier(accessor, ast.ModifierFlagsAbstract) { return c.grammarErrorAtPos(accessor, accessor.End()-1, len(";"), diagnostics.X_0_expected, "{") } @@ -1297,7 +1297,7 @@ func (c *Checker) checkGrammarAccessor(accessor *ast.AccessorDeclaration) bool { if ast.HasSyntacticModifier(accessor, ast.ModifierFlagsAbstract) { return c.grammarErrorOnNode(accessor, diagnostics.An_abstract_accessor_cannot_have_an_implementation) } - if accessor.Parent.Kind == ast.KindTypeLiteral || accessor.Parent.Kind == ast.KindInterfaceDeclaration { + if accessor.Parent().Kind == ast.KindTypeLiteral || accessor.Parent().Kind == ast.KindInterfaceDeclaration { return c.grammarErrorOnNode(body, diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts) } } @@ -1305,7 +1305,7 @@ func (c *Checker) checkGrammarAccessor(accessor *ast.AccessorDeclaration) bool { funcData := accessor.FunctionLikeData() var typeParameters *ast.NodeList if funcData != nil { - typeParameters = funcData.TypeParameters + typeParameters = funcData.TypeParameters() } if typeParameters != nil { @@ -1315,7 +1315,7 @@ func (c *Checker) checkGrammarAccessor(accessor *ast.AccessorDeclaration) bool { return c.grammarErrorOnNode(accessor.Name(), core.IfElse(accessor.Kind == ast.KindGetAccessor, diagnostics.A_get_accessor_cannot_have_parameters, diagnostics.A_set_accessor_must_have_exactly_one_parameter)) } if accessor.Kind == ast.KindSetAccessor { - if funcData.Type != nil { + if funcData.Type() != nil { return c.grammarErrorOnNode(accessor.Name(), diagnostics.A_set_accessor_cannot_have_a_return_type_annotation) } @@ -1324,13 +1324,13 @@ func (c *Checker) checkGrammarAccessor(accessor *ast.AccessorDeclaration) bool { panic("Return value does not match parameter count assertion.") } parameter := parameterNode.AsParameterDeclaration() - if parameter.DotDotDotToken != nil { - return c.grammarErrorOnNode(parameter.DotDotDotToken, diagnostics.A_set_accessor_cannot_have_rest_parameter) + if parameter.DotDotDotToken() != nil { + return c.grammarErrorOnNode(parameter.DotDotDotToken(), diagnostics.A_set_accessor_cannot_have_rest_parameter) } - if parameter.QuestionToken != nil { - return c.grammarErrorOnNode(parameter.QuestionToken, diagnostics.A_set_accessor_cannot_have_an_optional_parameter) + if parameter.QuestionToken() != nil { + return c.grammarErrorOnNode(parameter.QuestionToken(), diagnostics.A_set_accessor_cannot_have_an_optional_parameter) } - if parameter.Initializer != nil { + if parameter.Initializer() != nil { return c.grammarErrorOnNode(accessor.Name(), diagnostics.A_set_accessor_parameter_cannot_have_an_initializer) } } @@ -1350,11 +1350,11 @@ func (c *Checker) doesAccessorHaveCorrectParameterCount(accessor *ast.AccessorDe func (c *Checker) checkGrammarTypeOperatorNode(node *ast.TypeOperatorNode) bool { if node.Operator == ast.KindUniqueKeyword { - innerType := node.Type + innerType := node.Type() if innerType.Kind != ast.KindSymbolKeyword { return c.grammarErrorOnNode(innerType, diagnostics.X_0_expected, scanner.TokenToString(ast.KindSymbolKeyword)) } - parent := ast.WalkUpParenthesizedTypes(node.Parent) + parent := ast.WalkUpParenthesizedTypes(node.Parent()) switch parent.Kind { case ast.KindVariableDeclaration: decl := parent.AsVariableDeclaration() @@ -1364,7 +1364,7 @@ func (c *Checker) checkGrammarTypeOperatorNode(node *ast.TypeOperatorNode) bool if !isVariableDeclarationInVariableStatement(decl.AsNode()) { return c.grammarErrorOnNode(node.AsNode(), diagnostics.X_unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement) } - if decl.Parent.Flags&ast.NodeFlagsConst == 0 { + if decl.Parent().Flags&ast.NodeFlagsConst == 0 { return c.grammarErrorOnNode(parent.AsVariableDeclaration().Name(), diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const) } case ast.KindPropertyDeclaration: @@ -1379,7 +1379,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.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)) } @@ -1394,7 +1394,7 @@ func (c *Checker) checkGrammarForInvalidDynamicName(node *ast.DeclarationName, m } var expression *ast.Node if ast.IsElementAccessExpression(node) { - expression = ast.SkipParentheses(node.AsElementAccessExpression().ArgumentExpression) + expression = ast.SkipParentheses(node.AsElementAccessExpression().ArgumentExpression()) } else { expression = node.Expression() } @@ -1417,17 +1417,17 @@ func (c *Checker) checkGrammarMethod(node *ast.Node /*Union[MethodDeclaration, M } if node.Kind == ast.KindMethodDeclaration { - if node.Parent.Kind == ast.KindObjectLiteralExpression { + if node.Parent().Kind == ast.KindObjectLiteralExpression { // We only disallow modifier on a method declaration if it is a property of object-literal-expression if modifiers := node.Modifiers(); modifiers != nil && !(len(modifiers.Nodes) == 1 && modifiers.Nodes[0].Kind == ast.KindAsyncKeyword) { return c.grammarErrorOnFirstToken(node, diagnostics.Modifiers_cannot_appear_here) } methodDecl := node.AsMethodDeclaration() - if c.checkGrammarForInvalidQuestionMark(methodDecl.PostfixToken, diagnostics.An_object_member_cannot_be_declared_optional) { + if c.checkGrammarForInvalidQuestionMark(methodDecl.PostfixToken(), diagnostics.An_object_member_cannot_be_declared_optional) { return true } - if c.checkGrammarForInvalidExclamationToken(methodDecl.PostfixToken, diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context) { + if c.checkGrammarForInvalidExclamationToken(methodDecl.PostfixToken(), diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context) { return true } if node.Body() == nil { @@ -1439,7 +1439,7 @@ func (c *Checker) checkGrammarMethod(node *ast.Node /*Union[MethodDeclaration, M } } - if ast.IsClassLike(node.Parent) { + if ast.IsClassLike(node.Parent()) { // Technically, computed properties in ambient contexts is disallowed // for property declarations and accessors too, not just methods. // However, property declarations disallow computed names in general, @@ -1450,9 +1450,9 @@ func (c *Checker) checkGrammarMethod(node *ast.Node /*Union[MethodDeclaration, M } else if node.Kind == ast.KindMethodDeclaration && node.Body() == nil { return c.checkGrammarForInvalidDynamicName(node.Name(), diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type) } - } else if node.Parent.Kind == ast.KindInterfaceDeclaration { + } else if node.Parent().Kind == ast.KindInterfaceDeclaration { return c.checkGrammarForInvalidDynamicName(node.Name(), diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type) - } else if node.Parent.Kind == ast.KindTypeLiteral { + } else if node.Parent().Kind == ast.KindTypeLiteral { return c.checkGrammarForInvalidDynamicName(node.Name(), diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type) } @@ -1492,7 +1492,7 @@ func (c *Checker) checkGrammarBreakOrContinueStatement(node *ast.Node) bool { } } - current = current.Parent + current = current.Parent() } if targetLabel != nil { @@ -1516,21 +1516,21 @@ func (c *Checker) checkGrammarBreakOrContinueStatement(node *ast.Node) bool { } func (c *Checker) checkGrammarBindingElement(node *ast.BindingElement) bool { - if node.DotDotDotToken != nil { - elements := node.Parent.ElementList() + if node.DotDotDotToken() != nil { + 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) } c.checkGrammarForDisallowedTrailingComma(elements, diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma) - if node.PropertyName != nil { + if node.PropertyName() != nil { return c.grammarErrorOnNode(node.Name(), diagnostics.A_rest_element_cannot_have_a_property_name) } } - if node.DotDotDotToken != nil && node.Initializer != nil { + if node.DotDotDotToken() != nil && node.Initializer() != nil { // Error on equals token which immediately precedes the initializer - return c.grammarErrorAtPos(node.AsNode(), node.Initializer.Pos()-1, 1, diagnostics.A_rest_element_cannot_have_an_initializer) + return c.grammarErrorAtPos(node.AsNode(), node.Initializer().Pos()-1, 1, diagnostics.A_rest_element_cannot_have_an_initializer) } return false @@ -1548,11 +1548,11 @@ func (c *Checker) checkGrammarVariableDeclaration(node *ast.VariableDeclaration) } } - if node.Parent.Parent.Kind != ast.KindForInStatement && node.Parent.Parent.Kind != ast.KindForOfStatement { + if node.Parent().Parent().Kind != ast.KindForInStatement && node.Parent().Parent().Kind != ast.KindForOfStatement { if nodeFlags&ast.NodeFlagsAmbient != 0 { c.checkAmbientInitializer(node.AsNode()) - } else if node.Initializer == nil { - if ast.IsBindingPattern(node.Name()) && !ast.IsBindingPattern(node.Parent) { + } else if node.Initializer() == nil { + if ast.IsBindingPattern(node.Name()) && !ast.IsBindingPattern(node.Parent()) { return c.grammarErrorOnNode(node.AsNode(), diagnostics.A_destructuring_declaration_must_have_an_initializer) } switch blockScopeKind { @@ -1566,20 +1566,20 @@ func (c *Checker) checkGrammarVariableDeclaration(node *ast.VariableDeclaration) } } - if node.ExclamationToken != nil && (node.Parent.Parent.Kind != ast.KindVariableStatement || node.Type == nil || node.Initializer != nil || nodeFlags&ast.NodeFlagsAmbient != 0) { + if node.ExclamationToken() != nil && (node.Parent().Parent().Kind != ast.KindVariableStatement || node.Type() == nil || node.Initializer() != nil || nodeFlags&ast.NodeFlagsAmbient != 0) { var message *diagnostics.Message switch { - case node.Initializer != nil: + case node.Initializer() != nil: message = diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions - case node.Type == nil: + case node.Type() == nil: message = diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations default: message = diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context } - return c.grammarErrorOnNode(node.ExclamationToken, message) + return c.grammarErrorOnNode(node.ExclamationToken(), message) } - if c.program.GetEmitModuleFormatOfFile(ast.GetSourceFileOfNode(node.AsNode())) < core.ModuleKindSystem && (node.Parent.Parent.Flags&ast.NodeFlagsAmbient == 0) && ast.HasSyntacticModifier(node.Parent.Parent, ast.ModifierFlagsExport) { + if c.program.GetEmitModuleFormatOfFile(ast.GetSourceFileOfNode(node.AsNode())) < core.ModuleKindSystem && (node.Parent().Parent().Flags&ast.NodeFlagsAmbient == 0) && ast.HasSyntacticModifier(node.Parent().Parent(), ast.ModifierFlagsExport) { c.checkGrammarForEsModuleMarkerInBindingName(node.Name()) } @@ -1626,7 +1626,7 @@ func (c *Checker) checkGrammarNameInLetOrConstDeclarations(name *ast.Node /*Unio } func (c *Checker) checkGrammarVariableDeclarationList(declarationList *ast.VariableDeclarationList) bool { - declarations := declarationList.Declarations + declarations := declarationList.Declarations() if c.checkGrammarForDisallowedTrailingComma(declarations, diagnostics.Trailing_comma_not_allowed) { return true } @@ -1637,13 +1637,13 @@ func (c *Checker) checkGrammarVariableDeclarationList(declarationList *ast.Varia blockScopeFlags := declarationList.Flags & ast.NodeFlagsBlockScoped if blockScopeFlags == ast.NodeFlagsUsing || blockScopeFlags == ast.NodeFlagsAwaitUsing { - if ast.IsForInStatement(declarationList.Parent) { + if ast.IsForInStatement(declarationList.Parent()) { return c.grammarErrorOnNode(declarationList.AsNode(), core.IfElse(blockScopeFlags == ast.NodeFlagsUsing, diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration, diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration)) } if declarationList.Flags&ast.NodeFlagsAmbient != 0 { return c.grammarErrorOnNode(declarationList.AsNode(), core.IfElse(blockScopeFlags == ast.NodeFlagsUsing, diagnostics.X_using_declarations_are_not_allowed_in_ambient_contexts, diagnostics.X_await_using_declarations_are_not_allowed_in_ambient_contexts)) } - if ast.IsVariableStatement(declarationList.Parent) && (ast.IsCaseClause(declarationList.Parent.Parent) || ast.IsDefaultClause(declarationList.Parent.Parent)) { + if ast.IsVariableStatement(declarationList.Parent()) && (ast.IsCaseClause(declarationList.Parent().Parent()) || ast.IsDefaultClause(declarationList.Parent().Parent())) { return c.grammarErrorOnNode(declarationList.AsNode(), core.IfElse(blockScopeFlags == ast.NodeFlagsUsing, diagnostics.X_using_declarations_are_not_allowed_in_case_or_default_clauses_unless_contained_within_a_block, diagnostics.X_await_using_declarations_are_not_allowed_in_case_or_default_clauses_unless_contained_within_a_block)) } } @@ -1770,8 +1770,8 @@ func (c *Checker) checkGrammarYieldExpression(node *ast.Node) bool { } func (c *Checker) checkGrammarForDisallowedBlockScopedVariableStatement(node *ast.VariableStatement) bool { - if !c.containerAllowsBlockScopedVariable(node.Parent) { - blockScopeKind := c.getCombinedNodeFlagsCached(node.DeclarationList) & ast.NodeFlagsBlockScoped + if !c.containerAllowsBlockScopedVariable(node.Parent()) { + blockScopeKind := c.getCombinedNodeFlagsCached(node.DeclarationList()) & ast.NodeFlagsBlockScoped if blockScopeKind != 0 { var keyword string switch { @@ -1804,7 +1804,7 @@ func (c *Checker) containerAllowsBlockScopedVariable(parent *ast.Node) bool { ast.KindForOfStatement: return false case ast.KindLabeledStatement: - return c.containerAllowsBlockScopedVariable(parent.Parent) + return c.containerAllowsBlockScopedVariable(parent.Parent()) } return true @@ -1821,7 +1821,7 @@ func (c *Checker) checkGrammarMetaProperty(node *ast.MetaProperty) bool { } case ast.KindImportKeyword: if nameText != "meta" { - isCallee := ast.IsCallExpression(node.Parent) && node.Parent.Expression() == node.AsNode() + isCallee := ast.IsCallExpression(node.Parent()) && node.Parent().Expression() == node.AsNode() if ast.IsImportPhaseMetaProperty(node.AsNode()) { if !isCallee { return c.grammarErrorAtPos(node.AsNode(), node.AsNode().End(), 0, diagnostics.X_0_expected, "(") @@ -1839,7 +1839,7 @@ func (c *Checker) checkGrammarMetaProperty(node *ast.MetaProperty) bool { } func (c *Checker) checkGrammarConstructorTypeParameters(node *ast.ConstructorDeclaration) bool { - range_ := node.TypeParameters + range_ := node.TypeParameters() if range_ != nil { var pos int if range_.Pos() == range_.End() { @@ -1854,7 +1854,7 @@ func (c *Checker) checkGrammarConstructorTypeParameters(node *ast.ConstructorDec } func (c *Checker) checkGrammarConstructorTypeAnnotation(node *ast.ConstructorDeclaration) bool { - t := node.Type + t := node.Type() if t != nil { return c.grammarErrorOnNode(t, diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration) } @@ -1863,10 +1863,10 @@ func (c *Checker) checkGrammarConstructorTypeAnnotation(node *ast.ConstructorDec func (c *Checker) checkGrammarProperty(node *ast.Node /*Union[PropertyDeclaration, PropertySignature]*/) bool { propertyName := node.Name() - if ast.IsComputedPropertyName(propertyName) && ast.IsBinaryExpression(propertyName.Expression()) && propertyName.Expression().AsBinaryExpression().OperatorToken.Kind == ast.KindInKeyword { - return c.grammarErrorOnNode(node.Parent.Members()[0], diagnostics.A_mapped_type_may_not_declare_properties_or_methods) + if ast.IsComputedPropertyName(propertyName) && ast.IsBinaryExpression(propertyName.Expression()) && propertyName.Expression().AsBinaryExpression().OperatorToken().Kind == ast.KindInKeyword { + return c.grammarErrorOnNode(node.Parent().Members()[0], diagnostics.A_mapped_type_may_not_declare_properties_or_methods) } - if ast.IsClassLike(node.Parent) { + if ast.IsClassLike(node.Parent()) { if ast.IsStringLiteral(propertyName) && propertyName.Text() == "constructor" { return c.grammarErrorOnNode(propertyName, diagnostics.Classes_may_not_have_a_field_named_constructor) } @@ -1876,7 +1876,7 @@ func (c *Checker) checkGrammarProperty(node *ast.Node /*Union[PropertyDeclaratio if ast.IsAutoAccessorPropertyDeclaration(node) && c.checkGrammarForInvalidQuestionMark(node.PostfixToken(), diagnostics.An_accessor_property_cannot_be_declared_optional) { return true } - } else if ast.IsInterfaceDeclaration(node.Parent) { + } else if ast.IsInterfaceDeclaration(node.Parent()) { if c.checkGrammarForInvalidDynamicName(propertyName, diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type) { return true } @@ -1887,7 +1887,7 @@ func (c *Checker) checkGrammarProperty(node *ast.Node /*Union[PropertyDeclaratio if initializer := node.Initializer(); initializer != nil { return c.grammarErrorOnNode(initializer, diagnostics.An_interface_property_cannot_have_an_initializer) } - } else if ast.IsTypeLiteralNode(node.Parent) { + } else if ast.IsTypeLiteralNode(node.Parent()) { if c.checkGrammarForInvalidDynamicName(node.Name(), diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type) { return true } @@ -1906,14 +1906,14 @@ func (c *Checker) checkGrammarProperty(node *ast.Node /*Union[PropertyDeclaratio if ast.IsPropertyDeclaration(node) { propDecl := node.AsPropertyDeclaration() - postfixToken := propDecl.PostfixToken + postfixToken := propDecl.PostfixToken() if postfixToken != nil && postfixToken.Kind == ast.KindExclamationToken { switch { - case propDecl.Initializer != nil: + case propDecl.Initializer() != nil: return c.grammarErrorOnNode(postfixToken, diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions) - case propDecl.Type == nil: + case propDecl.Type() == nil: return c.grammarErrorOnNode(postfixToken, diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations) - case !ast.IsClassLike(node.Parent) || node.Flags&ast.NodeFlagsAmbient != 0 || ast.IsStatic(node) || ast.HasAbstractModifier(node): + case !ast.IsClassLike(node.Parent()) || node.Flags&ast.NodeFlagsAmbient != 0 || ast.IsStatic(node) || ast.HasAbstractModifier(node): return c.grammarErrorOnNode(postfixToken, diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context) } } @@ -1928,16 +1928,16 @@ func (c *Checker) checkAmbientInitializer(node *ast.Node) bool { switch node.Kind { case ast.KindVariableDeclaration: varDecl := node.AsVariableDeclaration() - initializer = varDecl.Initializer - typeNode = varDecl.Type + initializer = varDecl.Initializer() + typeNode = varDecl.Type() case ast.KindPropertyDeclaration: propDecl := node.AsPropertyDeclaration() - initializer = propDecl.Initializer - typeNode = propDecl.Type + initializer = propDecl.Initializer() + typeNode = propDecl.Type() case ast.KindPropertySignature: propSig := node.AsPropertySignatureDeclaration() - initializer = propSig.Initializer - typeNode = propSig.Type + initializer = propSig.Initializer() + typeNode = propSig.Type() default: panic(fmt.Sprintf("Unexpected node kind %q", node.Kind)) } @@ -1959,7 +1959,7 @@ func (c *Checker) checkAmbientInitializer(node *ast.Node) bool { func isInitializerStringOrNumberLiteralExpression(expr *ast.Expression) bool { return ast.IsStringOrNumericLiteralLike(expr) || - expr.Kind == ast.KindPrefixUnaryExpression && expr.AsPrefixUnaryExpression().Operator == ast.KindMinusToken && expr.AsPrefixUnaryExpression().Operand.Kind == ast.KindNumericLiteral + expr.Kind == ast.KindPrefixUnaryExpression && expr.AsPrefixUnaryExpression().Operator == ast.KindMinusToken && expr.AsPrefixUnaryExpression().Operand().Kind == ast.KindNumericLiteral } func isInitializerBigIntLiteralExpression(expr *ast.Expression) bool { @@ -1969,7 +1969,7 @@ func isInitializerBigIntLiteralExpression(expr *ast.Expression) bool { if expr.Kind == ast.KindPrefixUnaryExpression { unaryExpr := expr.AsPrefixUnaryExpression() - return unaryExpr.Operator == ast.KindMinusToken && unaryExpr.Operand.Kind == ast.KindBigIntLiteral + return unaryExpr.Operator == ast.KindMinusToken && unaryExpr.Operand().Kind == ast.KindBigIntLiteral } return false @@ -1983,8 +1983,8 @@ func (c *Checker) isInitializerSimpleLiteralEnumReference(expr *ast.Expression) if ast.IsElementAccessExpression(expr) { elementAccess := expr.AsElementAccessExpression() - return isInitializerStringOrNumberLiteralExpression(elementAccess.ArgumentExpression) && - ast.IsEntityNameExpression(elementAccess.Expression) && + return isInitializerStringOrNumberLiteralExpression(elementAccess.ArgumentExpression()) && + ast.IsEntityNameExpression(elementAccess.Expression()) && c.checkExpressionCached(expr).flags&TypeFlagsEnumLike != 0 } @@ -2030,7 +2030,7 @@ func (c *Checker) checkGrammarStatementInAmbientContext(node *ast.Node) bool { if node.Flags&ast.NodeFlagsAmbient != 0 { // Find containing block which is either Block, ModuleBlock, SourceFile links := c.nodeLinks.Get(node) - if !links.hasReportedStatementInAmbientContext && (ast.IsFunctionLike(node.Parent) || ast.IsAccessor(node.Parent)) { + if !links.hasReportedStatementInAmbientContext && (ast.IsFunctionLike(node.Parent()) || ast.IsAccessor(node.Parent())) { links.hasReportedStatementInAmbientContext = c.grammarErrorOnFirstToken(node, diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts) return links.hasReportedStatementInAmbientContext } @@ -2040,8 +2040,8 @@ func (c *Checker) checkGrammarStatementInAmbientContext(node *ast.Node) bool { // to prevent noisiness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // - if node.Parent.Kind == ast.KindBlock || node.Parent.Kind == ast.KindModuleBlock || node.Parent.Kind == ast.KindSourceFile { - links := c.nodeLinks.Get(node.Parent) + if node.Parent().Kind == ast.KindBlock || node.Parent().Kind == ast.KindModuleBlock || node.Parent().Kind == ast.KindSourceFile { + links := c.nodeLinks.Get(node.Parent()) // Check if the containing block ever report this error if !links.hasReportedStatementInAmbientContext { links.hasReportedStatementInAmbientContext = c.grammarErrorOnFirstToken(node, diagnostics.Statements_are_not_allowed_in_ambient_contexts) @@ -2085,7 +2085,7 @@ func (c *Checker) checkGrammarNumericLiteral(node *ast.NumericLiteral) { } func (c *Checker) checkGrammarBigIntLiteral(node *ast.BigIntLiteral) bool { - literalType := ast.IsLiteralTypeNode(node.Parent) || ast.IsPrefixUnaryExpression(node.Parent) && ast.IsLiteralTypeNode(node.Parent.Parent) + literalType := ast.IsLiteralTypeNode(node.Parent()) || ast.IsPrefixUnaryExpression(node.Parent()) && ast.IsLiteralTypeNode(node.Parent().Parent()) if !literalType { // Don't error on BigInt literals in ambient contexts if node.Flags&ast.NodeFlagsAmbient == 0 && c.languageVersion < core.ScriptTargetES2020 { @@ -2100,17 +2100,17 @@ func (c *Checker) checkGrammarBigIntLiteral(node *ast.BigIntLiteral) bool { func (c *Checker) checkGrammarImportClause(node *ast.ImportClause) bool { switch node.PhaseModifier { case ast.KindTypeKeyword: - if node.Flags&ast.NodeFlagsJSDoc == 0 && node.Name() != nil && node.NamedBindings != nil { + if node.Flags&ast.NodeFlagsJSDoc == 0 && node.Name() != nil && node.NamedBindings() != nil { return c.grammarErrorOnNode(&node.Node, diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both) } - if node.NamedBindings != nil && node.NamedBindings.Kind == ast.KindNamedImports { - return c.checkGrammarTypeOnlyNamedImportsOrExports(node.NamedBindings) + if node.NamedBindings() != nil && node.NamedBindings().Kind == ast.KindNamedImports { + return c.checkGrammarTypeOnlyNamedImportsOrExports(node.NamedBindings()) } case ast.KindDeferKeyword: if node.Name() != nil { return c.grammarErrorOnNode(&node.Node, diagnostics.Default_imports_are_not_allowed_in_a_deferred_import) } - if node.NamedBindings != nil && node.NamedBindings.Kind == ast.KindNamedImports { + if node.NamedBindings() != nil && node.NamedBindings().Kind == ast.KindNamedImports { return c.grammarErrorOnNode(&node.Node, diagnostics.Named_imports_are_not_allowed_in_a_deferred_import) } if c.moduleKind.SupportsDeferredImports() { @@ -2118,14 +2118,14 @@ func (c *Checker) checkGrammarImportClause(node *ast.ImportClause) bool { } return c.grammarErrorOnNode(&node.Node, diagnostics.Deferred_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_or_preserve) case ast.KindSourceKeyword: - if node.NamedBindings != nil { + if node.NamedBindings() != nil { return c.grammarErrorOnNode(&node.Node, diagnostics.Named_and_namespace_imports_are_not_allowed_in_a_source_phase_import) } if node.Name() == nil { return c.grammarErrorOnNode(&node.Node, diagnostics.A_source_phase_import_must_specify_a_local_binding) } if c.moduleKind.SupportsSourcePhaseImports() { - moduleSpecifier := getModuleSpecifierFromNode(node.Parent) + moduleSpecifier := getModuleSpecifierFromNode(node.Parent()) if c.getEmitSyntaxForModuleSpecifierExpression(moduleSpecifier) == core.ModuleKindCommonJS { return c.grammarErrorOnNode(&node.Node, diagnostics.Source_phase_imports_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls) } @@ -2138,8 +2138,8 @@ func (c *Checker) checkGrammarImportClause(node *ast.ImportClause) bool { func (c *Checker) checkGrammarImportAttributeValues(node *ast.ImportAttributes) bool { hasError := false - for _, attribute := range node.Attributes.Nodes { - value := attribute.AsImportAttribute().Value + for _, attribute := range node.Attributes().Nodes { + value := attribute.AsImportAttribute().Value() if ast.IsStringLiteral(value) { continue } @@ -2191,14 +2191,14 @@ func (c *Checker) checkGrammarImportCallExpression(node *ast.Node) bool { } nodeAsCall := node.AsCallExpression() - if ast.IsSourcePhaseImportCall(node) && nodeAsCall.QuestionDotToken != nil { - return c.grammarErrorOnNode(nodeAsCall.QuestionDotToken, diagnostics.Optional_chaining_cannot_be_used_with_import_source) + if ast.IsSourcePhaseImportCall(node) && nodeAsCall.QuestionDotToken() != nil { + return c.grammarErrorOnNode(nodeAsCall.QuestionDotToken(), diagnostics.Optional_chaining_cannot_be_used_with_import_source) } - if nodeAsCall.TypeArguments != nil { + if nodeAsCall.TypeArguments() != nil { return c.grammarErrorOnNode(node, diagnostics.This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot_have_type_arguments) } - nodeArguments := nodeAsCall.Arguments + nodeArguments := nodeAsCall.Arguments() argumentNodes := nodeArguments.Nodes if !(core.ModuleKindNode16 <= c.moduleKind && c.moduleKind <= core.ModuleKindNodeNext) && c.moduleKind != core.ModuleKindESNext && c.moduleKind != core.ModuleKindPreserve { // We are allowed trailing comma after proposal-import-assertions. @@ -2224,7 +2224,7 @@ func (c *Checker) checkGrammarImportCallExpression(node *ast.Node) bool { } func (c *Checker) checkGrammarImportAttributesType(attributes *ast.TypeLiteralNode) bool { - members := attributes.Members + members := attributes.Members() if members == nil { return false } @@ -2240,7 +2240,7 @@ func (c *Checker) checkGrammarImportAttributesType(attributes *ast.TypeLiteralNo } } } - if propertySignature.Type == nil { + if propertySignature.Type() == nil { return c.grammarErrorOnNode(member, diagnostics.An_import_attributes_property_must_have_a_type_annotation) } if propertySignature.QuestionToken() != nil { @@ -2254,8 +2254,8 @@ func (c *Checker) checkGrammarImportAttributesType(attributes *ast.TypeLiteralNo return c.grammarErrorOnNode(name, diagnostics.X_0_is_not_a_valid_key_for_an_import_attributes_type, name.Text()) } - typeNode := propertySignature.Type - if !ast.IsLiteralTypeNode(typeNode) || !ast.IsStringLiteral(typeNode.AsLiteralTypeNode().Literal) { + typeNode := propertySignature.Type() + if !ast.IsLiteralTypeNode(typeNode) || !ast.IsStringLiteral(typeNode.AsLiteralTypeNode().Literal()) { return c.grammarErrorOnNode(typeNode, diagnostics.An_import_attributes_property_must_have_a_string_literal_type_annotation) } } diff --git a/tsc/internal/checker/inference.go b/tsc/internal/checker/inference.go index 43f0930bfc5a2..7f7c93737f91b 100644 --- a/tsc/internal/checker/inference.go +++ b/tsc/internal/checker/inference.go @@ -716,7 +716,7 @@ func (c *Checker) inferFromObjectTypes(n *InferenceState, source *Type, target * if c.isGenericMappedType(source) && c.isGenericMappedType(target) { c.inferFromGenericMappedTypes(n, source, target) } - if target.objectFlags&ObjectFlagsMapped != 0 && target.AsMappedType().declaration.NameType == nil { + if target.objectFlags&ObjectFlagsMapped != 0 && target.AsMappedType().declaration.NameType() == nil { constraintType := c.getConstraintTypeFromMappedType(target) if c.inferToMappedType(n, source, target, constraintType) { return @@ -1671,7 +1671,7 @@ func hasInferenceCandidatesOrDefault(info *InferenceInfo) bool { func hasTypeParameterDefault(tp *Type) bool { if tp.symbol != nil { for _, d := range tp.symbol.Declarations { - if ast.IsTypeParameterDeclaration(d) && d.AsTypeParameterDeclaration().DefaultType != nil { + if ast.IsTypeParameterDeclaration(d) && d.AsTypeParameterDeclaration().DefaultType() != nil { return true } } diff --git a/tsc/internal/checker/jsdoc.go b/tsc/internal/checker/jsdoc.go index c8b5fb1adba44..5638e9d327273 100644 --- a/tsc/internal/checker/jsdoc.go +++ b/tsc/internal/checker/jsdoc.go @@ -45,10 +45,10 @@ func (c *Checker) checkUnmatchedJSDocParameters(node *ast.Node) { if excludedParameters.Has(lastJSDocParamIndex) || parameters.Has(lastJSDocParam.Name().Text()) { return } - if lastJSDocParam.TypeExpression == nil || lastJSDocParam.TypeExpression.Type() == nil { + if lastJSDocParam.TypeExpression() == nil || lastJSDocParam.TypeExpression().Type() == nil { return } - if c.isArrayType(c.getTypeFromTypeNode(lastJSDocParam.TypeExpression.Type())) { + if c.isArrayType(c.getTypeFromTypeNode(lastJSDocParam.TypeExpression().Type())) { return } c.error(lastJSDocParam.Name(), diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, lastJSDocParam.Name().Text()) @@ -67,7 +67,7 @@ func (c *Checker) checkUnmatchedJSDocParameters(node *ast.Node) { c.error( name, diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, entityNameToString(name), - entityNameToString(name.AsQualifiedName().Left), + entityNameToString(name.AsQualifiedName().Left()), ) } } else { @@ -91,8 +91,8 @@ func getAllJSDocTags(node *ast.Node) []*ast.Node { continue } lastJSDoc := jsdocs[len(jsdocs)-1].AsJSDoc() - if lastJSDoc.Tags != nil { - return lastJSDoc.Tags.Nodes + if lastJSDoc.Tags() != nil { + return lastJSDoc.Tags().Nodes } } } diff --git a/tsc/internal/checker/jsx.go b/tsc/internal/checker/jsx.go index e05f24634cc7f..95d9412d7ca52 100644 --- a/tsc/internal/checker/jsx.go +++ b/tsc/internal/checker/jsx.go @@ -76,12 +76,12 @@ func (c *Checker) checkJsxElement(node *ast.Node, checkMode CheckMode) *Type { func (c *Checker) checkJsxElementDeferred(node *ast.Node) { jsxElement := node.AsJsxElement() - c.checkJsxOpeningLikeElementOrOpeningFragment(jsxElement.OpeningElement) + c.checkJsxOpeningLikeElementOrOpeningFragment(jsxElement.OpeningElement()) // Perform resolution on the closing tag so that rename/go to definition/etc work - if isJsxIntrinsicTagName(jsxElement.ClosingElement.TagName()) { - c.getIntrinsicTagSymbol(jsxElement.ClosingElement) + if isJsxIntrinsicTagName(jsxElement.ClosingElement().TagName()) { + c.getIntrinsicTagSymbol(jsxElement.ClosingElement()) } else { - c.checkExpression(jsxElement.ClosingElement.TagName()) + c.checkExpression(jsxElement.ClosingElement().TagName()) } c.checkJsxChildren(node, CheckModeNormal) } @@ -92,7 +92,7 @@ func (c *Checker) checkJsxExpression(node *ast.Node, checkMode CheckMode) *Type return c.errorType } t := c.checkExpressionEx(node.Expression(), checkMode) - if node.AsJsxExpression().DotDotDotToken != nil && t != c.anyType && !c.isArrayType(t) { + if node.AsJsxExpression().DotDotDotToken() != nil && t != c.anyType && !c.isArrayType(t) { c.error(node, diagnostics.JSX_spread_child_must_be_an_array_type) } return t @@ -108,7 +108,7 @@ func (c *Checker) checkJsxSelfClosingElementDeferred(node *ast.Node) { } func (c *Checker) checkJsxFragment(node *ast.Node) *Type { - c.checkJsxOpeningLikeElementOrOpeningFragment(node.AsJsxFragment().OpeningFragment) + c.checkJsxOpeningLikeElementOrOpeningFragment(node.AsJsxFragment().OpeningFragment()) // by default, jsx:'react' will use jsxFactory = React.createElement and jsxFragmentFactory = React.Fragment // if jsxFactory compiler option is provided, ensure jsxFragmentFactory compiler option or @jsxFrag pragma is provided too nodeSourceFile := ast.GetSourceFileOfNode(node) @@ -125,7 +125,7 @@ func (c *Checker) checkJsxFragment(node *ast.Node) *Type { func (c *Checker) checkJsxAttributes(node *ast.Node, checkMode CheckMode) *Type { c.checkNodeDeferred(node) - return c.createJsxAttributesTypeFromAttributesProperty(node.Parent, checkMode) + return c.createJsxAttributesTypeFromAttributesProperty(node.Parent(), checkMode) } func (c *Checker) checkJsxOpeningLikeElementOrOpeningFragment(node *ast.Node) { @@ -204,10 +204,10 @@ func (c *Checker) inferJsxTypeArguments(node *ast.Node, signature *Signature, ch func (c *Checker) getContextualTypeForJsxExpression(node *ast.Node, contextFlags ContextFlags) *Type { switch { - case ast.IsJsxAttributeLike(node.Parent): + case ast.IsJsxAttributeLike(node.Parent()): return c.getContextualType(node, contextFlags) - case ast.IsJsxElement(node.Parent): - return c.getContextualTypeForChildJsxExpression(node.Parent, node, contextFlags) + case ast.IsJsxElement(node.Parent()): + return c.getContextualTypeForChildJsxExpression(node.Parent(), node, contextFlags) } return nil } @@ -217,18 +217,18 @@ func (c *Checker) getContextualTypeForJsxAttribute(attribute *ast.Node, contextF // which is a type of the parameter of the signature we are trying out. // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName if ast.IsJsxAttribute(attribute) { - attributesType := c.getApparentTypeOfContextualType(attribute.Parent, contextFlags) + attributesType := c.getApparentTypeOfContextualType(attribute.Parent(), contextFlags) if attributesType == nil || IsTypeAny(attributesType) { return nil } return c.getTypeOfPropertyOfContextualType(attributesType, attribute.Name().Text()) } - return c.getContextualType(attribute.Parent, contextFlags) + return c.getContextualType(attribute.Parent(), contextFlags) } func (c *Checker) getContextualJsxElementAttributesType(node *ast.Node, contextFlags ContextFlags) *Type { if ast.IsJsxOpeningElement(node) && contextFlags != ContextFlagsIgnoreNodeInferences { - index := c.findContextualNode(node.Parent, contextFlags == ContextFlagsNone) + index := c.findContextualNode(node.Parent(), contextFlags == ContextFlagsNone) if index >= 0 { // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type @@ -240,7 +240,7 @@ func (c *Checker) getContextualJsxElementAttributesType(node *ast.Node, contextF } func (c *Checker) getContextualTypeForChildJsxExpression(node *ast.Node, child *ast.JsxChild, contextFlags ContextFlags) *Type { - attributesType := c.getApparentTypeOfContextualType(node.AsJsxElement().OpeningElement.Attributes(), contextFlags) + attributesType := c.getApparentTypeOfContextualType(node.AsJsxElement().OpeningElement().Attributes(), contextFlags) // JSX expression is in children of JSX Element, we will look for an "children" attribute (we get the name from JSX.ElementAttributesProperty) jsxChildrenPropertyName := c.getJsxElementChildrenPropertyName(c.getJsxNamespaceAt(node)) if !(attributesType != nil && !IsTypeAny(attributesType) && jsxChildrenPropertyName != ast.InternalSymbolNameMissing && jsxChildrenPropertyName != "") { @@ -281,7 +281,7 @@ func (c *Checker) discriminateContextualTypeByJSXAttributes(node *ast.Node, cont if s.Flags&ast.SymbolFlagsOptional == 0 || node.Symbol() == nil { return false } - element := node.Parent.Parent + element := node.Parent().Parent() if s.Name == jsxChildrenPropertyName && ast.IsJsxElement(element) && len(ast.GetSemanticJsxChildren(element.Children().Nodes)) != 0 { return false } @@ -303,8 +303,8 @@ func (c *Checker) elaborateJsxComponents(node *ast.Node, source *Type, target *T } } } - if ast.IsJsxOpeningElement(node.Parent) && ast.IsJsxElement(node.Parent.Parent) { - containingElement := node.Parent.Parent // Containing JSXElement + if ast.IsJsxOpeningElement(node.Parent()) && ast.IsJsxElement(node.Parent().Parent()) { + containingElement := node.Parent().Parent() // Containing JSXElement childrenPropName := c.getJsxElementChildrenPropertyName(c.getJsxNamespaceAt(node)) if childrenPropName == ast.InternalSymbolNameMissing { childrenPropName = "children" @@ -331,7 +331,7 @@ func (c *Checker) elaborateJsxComponents(node *ast.Node, source *Type, target *T var invalidTextDiagnosticArgs []any getInvalidTextualChildDiagnostic := func() (*diagnostics.Message, []any) { if invalidTextDiagnostic == nil { - tagNameText := scanner.GetTextOfNode(node.Parent.TagName()) + tagNameText := scanner.GetTextOfNode(node.Parent().TagName()) invalidTextDiagnostic = diagnostics.X_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2 invalidTextDiagnosticArgs = []any{tagNameText, childrenPropName, c.TypeToString(childrenTargetType)} } @@ -344,7 +344,7 @@ func (c *Checker) elaborateJsxComponents(node *ast.Node, source *Type, target *T reportedError = c.elaborateIterableOrArrayLikeTargetElementwise(children, realSource, arrayLikeTargetParts, relation, diagnosticOutput) || reportedError } else if !c.isTypeRelatedTo(c.getIndexedAccessType(source, childrenNameType), childrenTargetType, relation) { // arity mismatch - diag := c.error(containingElement.AsJsxElement().OpeningElement.TagName(), diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided, childrenPropName, c.TypeToString(childrenTargetType)) + diag := c.error(containingElement.AsJsxElement().OpeningElement().TagName(), diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided, childrenPropName, c.TypeToString(childrenTargetType)) c.reportDiagnostic(diag, diagnosticOutput) reportedError = true } @@ -357,7 +357,7 @@ func (c *Checker) elaborateJsxComponents(node *ast.Node, source *Type, target *T } } else if !c.isTypeRelatedTo(c.getIndexedAccessType(source, childrenNameType), childrenTargetType, relation) { // arity mismatch - diag := c.error(containingElement.AsJsxElement().OpeningElement.TagName(), diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided, childrenPropName, c.TypeToString(childrenTargetType)) + diag := c.error(containingElement.AsJsxElement().OpeningElement().TagName(), diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided, childrenPropName, c.TypeToString(childrenTargetType)) c.reportDiagnostic(diag, diagnosticOutput) reportedError = true } @@ -797,7 +797,7 @@ func (c *Checker) createJsxAttributesTypeFromAttributesProperty(openingLikeEleme } parentHasSemanticJsxChildren := func(openingLikeElement *ast.Node) bool { // Handle children attribute - parent := openingLikeElement.Parent + parent := openingLikeElement.Parent() if parent == nil { return false } @@ -806,18 +806,18 @@ func (c *Checker) createJsxAttributesTypeFromAttributesProperty(openingLikeEleme switch { 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 { + if parent.AsJsxElement().OpeningElement() == openingLikeElement { children = parent.Children().Nodes } case ast.IsJsxFragment(parent): - if parent.AsJsxFragment().OpeningFragment == openingLikeElement { + if parent.AsJsxFragment().OpeningFragment() == openingLikeElement { children = parent.Children().Nodes } } return len(ast.GetSemanticJsxChildren(children)) != 0 } if parentHasSemanticJsxChildren(openingLikeElement) { - var childTypes []*Type = c.checkJsxChildren(openingLikeElement.Parent, checkMode) + var childTypes []*Type = c.checkJsxChildren(openingLikeElement.Parent(), checkMode) if !hasSpreadAnyType && jsxChildrenPropertyName != ast.InternalSymbolNameMissing && jsxChildrenPropertyName != "" { // Error if there is a attribute named "children" explicitly specified and children element. // This is because children element will overwrite the value from attributes. @@ -844,8 +844,8 @@ func (c *Checker) createJsxAttributesTypeFromAttributesProperty(openingLikeEleme } // Fake up a property declaration for the children childrenPropSymbol.ValueDeclaration = c.factory.NewPropertySignatureDeclaration(nil, c.factory.NewIdentifier(jsxChildrenPropertyName), nil /*postfixToken*/, nil /*type*/, nil /*initializer*/) - childrenPropSymbol.ValueDeclaration.Parent = attributeParent - childrenPropSymbol.ValueDeclaration.AsPropertySignatureDeclaration().Symbol = childrenPropSymbol + childrenPropSymbol.ValueDeclaration.SetParent(attributeParent) + ast.SetSymbol(childrenPropSymbol.ValueDeclaration, childrenPropSymbol) childPropMap := make(ast.SymbolTable) childPropMap[jsxChildrenPropertyName] = childrenPropSymbol spread = c.getSpreadType(spread, c.newAnonymousType(attributesSymbol, childPropMap, nil, nil, nil), attributesSymbol, objectFlags|c.getPropagatingFlagsOfTypes(childTypes, TypeFlagsNone), false /*readonly*/) @@ -1461,7 +1461,7 @@ func (c *Checker) getJsxNamespaceContainerForImplicitImport(location *ast.Node) return true } if ast.IsJsxFragment(node) { - links.firstJSXTagInFile = node.AsJsxFragment().OpeningFragment // to match strada, fragments issue errors on the opening fragment instead of the whole tag + links.firstJSXTagInFile = node.AsJsxFragment().OpeningFragment() // to match strada, fragments issue errors on the opening fragment instead of the whole tag return true } return node.ForEachChild(visit) diff --git a/tsc/internal/checker/nodebuilder.go b/tsc/internal/checker/nodebuilder.go index e6ccb962191f7..92204d935c51f 100644 --- a/tsc/internal/checker/nodebuilder.go +++ b/tsc/internal/checker/nodebuilder.go @@ -201,9 +201,9 @@ func simplifyClassDeclaration(f *ast.NodeFactory, classDecl *ast.Node, symbol *a cd, classDecl.Modifiers(), nil, - cd.TypeParameters, - cd.HeritageClauses, - cd.Members, + cd.TypeParameters(), + cd.HeritageClauses(), + cd.Members(), ) } return ast.ReplaceModifiers(f, classDecl, f.NewModifierList(ast.CreateModifiersFromModifierFlags(modifiers, f.NewModifier))) diff --git a/tsc/internal/checker/nodebuilder_hover.go b/tsc/internal/checker/nodebuilder_hover.go index d07e229b20451..efea79310f1ef 100644 --- a/tsc/internal/checker/nodebuilder_hover.go +++ b/tsc/internal/checker/nodebuilder_hover.go @@ -66,8 +66,8 @@ func (b *NodeBuilderImpl) expandEnumDecl(symbol *ast.Symbol) *ast.Node { } memberDecl := core.Find(p.Declarations, ast.IsEnumMember) var initializer *ast.Node - if memberDecl != nil && memberDecl.AsEnumMember().Initializer != nil { - initializer = b.f.DeepCloneNode(memberDecl.AsEnumMember().Initializer) + if memberDecl != nil && memberDecl.AsEnumMember().Initializer() != nil { + initializer = b.f.DeepCloneNode(memberDecl.AsEnumMember().Initializer()) } else { initializer = b.enumMemberInitializer(p) } @@ -219,10 +219,10 @@ func typeElementsToClassElements(f *ast.NodeFactory, members []*ast.Node) []*ast switch m.Kind { case ast.KindPropertySignature: ps := m.AsPropertySignatureDeclaration() - members[i] = f.NewPropertyDeclaration(m.Modifiers(), ps.Name(), ps.QuestionToken(), ps.Type, nil) + members[i] = f.NewPropertyDeclaration(m.Modifiers(), ps.Name(), ps.QuestionToken(), ps.Type(), nil) case ast.KindMethodSignature: ms := m.AsMethodSignatureDeclaration() - members[i] = f.NewMethodDeclaration(m.Modifiers(), nil, ms.Name(), ms.QuestionToken(), ms.TypeParameters, ms.Parameters, ms.Type, nil, nil) + members[i] = f.NewMethodDeclaration(m.Modifiers(), nil, ms.Name(), ms.QuestionToken(), ms.TypeParameters(), ms.Parameters(), ms.Type(), nil, nil) } } return members @@ -546,9 +546,9 @@ func (b *NodeBuilderImpl) expandModuleDecl(symbol *ast.Symbol) *ast.Node { } var attributes *ast.TypeLiteralNodeNode if declaration := core.Find(symbol.Declarations, func(declaration *ast.Node) bool { - return ast.IsModuleDeclaration(declaration) && declaration.AsModuleDeclaration().Attributes != nil + return ast.IsModuleDeclaration(declaration) && declaration.AsModuleDeclaration().Attributes() != nil }); declaration != nil { - attributes = b.f.DeepCloneNode(declaration.AsModuleDeclaration().Attributes) + attributes = b.f.DeepCloneNode(declaration.AsModuleDeclaration().Attributes()) b.e.SetEmitFlags(attributes, printer.EFSingleLine) } return b.f.NewModuleDeclaration(nil, keyword, localName, attributes, b.f.NewModuleBlock(b.f.NewNodeList(bodyStatements))) @@ -597,7 +597,7 @@ func (b *NodeBuilderImpl) filterInheritedProperties(t *Type, baseTypes []*Type, func (b *NodeBuilderImpl) isNamespaceMember(p *ast.Symbol) bool { return p.Flags&(ast.SymbolFlagsType|ast.SymbolFlagsNamespace|ast.SymbolFlagsAlias) != 0 || - !(p.Flags&ast.SymbolFlagsPrototype != 0 || p.Name == "prototype" || (p.ValueDeclaration != nil && ast.HasStaticModifier(p.ValueDeclaration) && ast.IsClassLike(p.ValueDeclaration.Parent))) + !(p.Flags&ast.SymbolFlagsPrototype != 0 || p.Name == "prototype" || (p.ValueDeclaration != nil && ast.HasStaticModifier(p.ValueDeclaration) && ast.IsClassLike(p.ValueDeclaration.Parent()))) } func isHashPrivate(s *ast.Symbol) bool { diff --git a/tsc/internal/checker/nodebuilderimpl.go b/tsc/internal/checker/nodebuilderimpl.go index 4592b3c656c43..3b4a81dc86e6a 100644 --- a/tsc/internal/checker/nodebuilderimpl.go +++ b/tsc/internal/checker/nodebuilderimpl.go @@ -292,7 +292,7 @@ func (b *NodeBuilderImpl) appendReferenceToType(root *ast.TypeNode, ref *ast.Typ imprt := root.AsImportTypeNode() // then move qualifiers ids := getAccessStack(ref) - qualifier := root.AsImportTypeNode().Qualifier + qualifier := root.AsImportTypeNode().Qualifier() for _, id := range ids { if qualifier != nil { qualifier = b.f.NewQualifiedName(qualifier, id) @@ -300,17 +300,17 @@ 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.TypeArgumentList()) + return b.f.UpdateImportTypeNode(imprt, imprt.IsTypeOf, imprt.Argument(), imprt.Attributes(), qualifier, ref.TypeArgumentList()) } else if ast.IsTypeReferenceNode(root) { typeRef := root.AsTypeReferenceNode() - if b.ctx.flags&nodebuilder.FlagsUseInstantiationExpressions != 0 && typeRef.TypeArguments != nil && len(typeRef.TypeArguments.Nodes) != 0 { - expr := b.createExpressionWithTypeArguments(b.createAccessExpression(typeRef.TypeName), typeRef.TypeArguments) + if b.ctx.flags&nodebuilder.FlagsUseInstantiationExpressions != 0 && typeRef.TypeArguments() != nil && len(typeRef.TypeArguments().Nodes) != 0 { + expr := b.createExpressionWithTypeArguments(b.createAccessExpression(typeRef.TypeName()), typeRef.TypeArguments()) for _, id := range getAccessStack(ref) { expr = b.f.NewPropertyAccessExpression(expr, nil, id, ast.NodeFlagsNone) } return expr } - var typeName *ast.Node = typeRef.TypeName + var typeName *ast.Node = typeRef.TypeName() for _, id := range getAccessStack(ref) { typeName = b.f.NewQualifiedName(typeName, id) } @@ -324,12 +324,12 @@ func (b *NodeBuilderImpl) appendReferenceToType(root *ast.TypeNode, ref *ast.Typ } func getAccessStack(ref *ast.Node) []*ast.Node { - var state *ast.Node = ref.AsTypeReferenceNode().TypeName + var state *ast.Node = ref.AsTypeReferenceNode().TypeName() ids := []*ast.Node{} for !ast.IsIdentifier(state) { entity := state.AsQualifiedName() - ids = append([]*ast.Node{entity.Right}, ids...) - state = entity.Left + ids = append([]*ast.Node{entity.Right()}, ids...) + state = entity.Left() } ids = append([]*ast.Node{state}, ids...) return ids @@ -410,7 +410,7 @@ func (b *NodeBuilderImpl) mapToTypeNodes(list []*Type, isBareList bool) *ast.Nod if typeNode != nil { result = append(result, typeNode) if seenNames != nil && isIdentifierTypeReference(typeNode) { - seenNames.Add(typeNode.AsTypeReferenceNode().TypeName.Text(), seenName{t, len(result) - 1}) + seenNames.Add(typeNode.AsTypeReferenceNode().TypeName().Text(), seenName{t, len(result) - 1}) } } } @@ -462,7 +462,7 @@ func (b *NodeBuilderImpl) serializeTypeName(node *ast.Node, isTypeOf bool, typeA } func isIdentifierTypeReference(node *ast.Node) bool { - return ast.IsTypeReferenceNode(node) && ast.IsIdentifier(node.AsTypeReferenceNode().TypeName) + return ast.IsTypeReferenceNode(node) && ast.IsIdentifier(node.AsTypeReferenceNode().TypeName()) } func arrayIsHomogeneous[T any](array []T, comparer func(a, B T) bool) bool { @@ -510,7 +510,7 @@ func (b *NodeBuilderImpl) canReuseExistingJSTypeNode(existing *ast.TypeNode, t * } func (b *NodeBuilderImpl) tryGetResolvedSymbolFromTypeNode(node *ast.Node) *ast.Symbol { - if node == nil || node.Parent == nil { + if node == nil || node.Parent() == nil { return nil } b.ch.getTypeFromTypeNode(node) @@ -718,10 +718,10 @@ func (b *NodeBuilderImpl) symbolToTypeNode(symbol *ast.Symbol, mask ast.SymbolFl } splitNode := getTopmostIndexedAccessType(nonRootParts.AsIndexedAccessTypeNode()) - qualifier := splitNode.ObjectType.AsTypeReferenceNode().TypeName + qualifier := splitNode.ObjectType().AsTypeReferenceNode().TypeName() return b.f.NewIndexedAccessTypeNode( b.f.NewImportTypeNode(isTypeOf, lit, attributes, qualifier, typeParameterNodes), - splitNode.IndexType, + splitNode.IndexType(), ) } @@ -738,14 +738,14 @@ func (b *NodeBuilderImpl) symbolToTypeNode(symbol *ast.Symbol, mask ast.SymbolFl } if isTypeOf && ast.IsExpressionWithTypeArguments(entityName) { expr := entityName.AsExpressionWithTypeArguments() - return b.f.NewTypeQueryNode(b.f.DeepCloneNode(expr.Expression), expr.TypeArguments) + return b.f.NewTypeQueryNode(b.f.DeepCloneNode(expr.Expression()), expr.TypeArguments()) } return entityName } func getTopmostIndexedAccessType(node *ast.IndexedAccessTypeNode) *ast.IndexedAccessTypeNode { - if ast.IsIndexedAccessTypeNode(node.ObjectType) { - return getTopmostIndexedAccessType(node.ObjectType.AsIndexedAccessTypeNode()) + if ast.IsIndexedAccessTypeNode(node.ObjectType()) { + return getTopmostIndexedAccessType(node.ObjectType().AsIndexedAccessTypeNode()) } return node } @@ -1003,8 +1003,8 @@ func (b *NodeBuilderImpl) getNameOfSymbolAsWritten(symbol *ast.Symbol) string { return scanner.DeclarationNameToString(name) } declaration := symbol.Declarations[0] // Declaration may be nameless, but we'll try anyway - if declaration.Parent != nil && declaration.Parent.Kind == ast.KindVariableDeclaration { - return scanner.DeclarationNameToString(declaration.Parent.AsVariableDeclaration().Name()) + if declaration.Parent() != nil && declaration.Parent().Kind == ast.KindVariableDeclaration { + return scanner.DeclarationNameToString(declaration.Parent().AsVariableDeclaration().Name()) } if ast.IsClassExpression(declaration) || ast.IsFunctionExpression(declaration) || ast.IsArrowFunction(declaration) { if b.ctx != nil && !b.ctx.encounteredError && b.ctx.flags&nodebuilder.FlagsAllowAnonymousIdentifier == 0 { @@ -1212,33 +1212,33 @@ func tryGetModuleSpecifierFromDeclarationWorker(node *ast.Node) *ast.Node { case ast.KindImportDeclaration, ast.KindExportDeclaration, ast.KindJSDocImportTag: return node.ModuleSpecifier() case ast.KindImportEqualsDeclaration: - ref := node.AsImportEqualsDeclaration().ModuleReference + ref := node.AsImportEqualsDeclaration().ModuleReference() if ref.Kind != ast.KindExternalModuleReference { return nil } return ref.Expression() case ast.KindImportClause: - if ast.IsImportDeclaration(node.Parent) { - return node.Parent.ModuleSpecifier() + if ast.IsImportDeclaration(node.Parent()) { + return node.Parent().ModuleSpecifier() } - return node.Parent.ModuleSpecifier() + return node.Parent().ModuleSpecifier() case ast.KindNamespaceExport: - return node.Parent.ModuleSpecifier() + return node.Parent().ModuleSpecifier() case ast.KindNamespaceImport: - if ast.IsImportDeclaration(node.Parent.Parent) { - return node.Parent.Parent.ModuleSpecifier() + if ast.IsImportDeclaration(node.Parent().Parent()) { + return node.Parent().Parent().ModuleSpecifier() } - return node.Parent.Parent.ModuleSpecifier() + return node.Parent().Parent().ModuleSpecifier() case ast.KindExportSpecifier: - return node.Parent.Parent.ModuleSpecifier() + return node.Parent().Parent().ModuleSpecifier() case ast.KindImportSpecifier: - if ast.IsImportDeclaration(node.Parent.Parent.Parent) { - return node.Parent.Parent.Parent.ModuleSpecifier() + if ast.IsImportDeclaration(node.Parent().Parent().Parent()) { + return node.Parent().Parent().Parent().ModuleSpecifier() } - return node.Parent.Parent.Parent.ModuleSpecifier() + return node.Parent().Parent().Parent().ModuleSpecifier() case ast.KindImportType: if ast.IsLiteralImportTypeNode(node) { - return node.AsImportTypeNode().Argument.AsLiteralTypeNode().Literal + return node.AsImportTypeNode().Argument().AsLiteralTypeNode().Literal() } return nil default: @@ -1532,12 +1532,12 @@ func (b *NodeBuilderImpl) createMappedTypeNodeFromType(t *Type) *ast.TypeNode { debug.Assert(t.Flags()&TypeFlagsObject != 0) mapped := t.AsMappedType() var readonlyToken *ast.Node - if mapped.declaration.ReadonlyToken != nil { - readonlyToken = b.f.NewToken(mapped.declaration.ReadonlyToken.Kind) + if mapped.declaration.ReadonlyToken() != nil { + readonlyToken = b.f.NewToken(mapped.declaration.ReadonlyToken().Kind) } var questionToken *ast.Node - if mapped.declaration.QuestionToken != nil { - questionToken = b.f.NewToken(mapped.declaration.QuestionToken.Kind) + if mapped.declaration.QuestionToken() != nil { + questionToken = b.f.NewToken(mapped.declaration.QuestionToken().Kind) } var appropriateConstraintTypeNode *ast.Node var newTypeVariable *ast.Node @@ -1584,7 +1584,7 @@ func (b *NodeBuilderImpl) createMappedTypeNodeFromType(t *Type) *ast.TypeNode { cleanup := b.enterNewScope(mapped.declaration.AsNode(), nil, []*Type{b.ch.getTypeParameterFromMappedType(t)}, nil, nil) typeParameterDeclarationNode := b.typeParameterToDeclarationWithConstraint(typeParameter, appropriateConstraintTypeNode) var nameTypeNode *ast.Node - if mapped.declaration.NameType != nil { + if mapped.declaration.NameType() != nil { nameTypeNode = b.typeToTypeNode(b.ch.getNameTypeFromMappedType(t)) } templateTypeNode := b.typeToTypeNode(b.ch.removeMissingType( @@ -1608,7 +1608,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.AsTypeParameterDeclaration().Constraint.Type(), false) + rawConstraintTypeFromDeclaration := b.getTypeFromTypeNode(mapped.declaration.TypeParameter().AsTypeParameterDeclaration().Constraint().Type(), false) if rawConstraintTypeFromDeclaration != nil { rawConstraintTypeFromDeclaration = b.ch.getConstraintOfTypeParameter(rawConstraintTypeFromDeclaration) } @@ -1624,7 +1624,7 @@ func (b *NodeBuilderImpl) createMappedTypeNodeFromType(t *Type) *ast.TypeNode { return b.f.NewConditionalTypeNode( b.typeToTypeNode(b.ch.getModifiersTypeFromMappedType(t)), - b.f.NewInferTypeNode(b.f.NewTypeParameterDeclaration(nil, newTypeVariable.AsTypeReferenceNode().TypeName.Clone(b.f), originalConstraintNode, nil, nil)), + b.f.NewInferTypeNode(b.f.NewTypeParameterDeclaration(nil, newTypeVariable.AsTypeReferenceNode().TypeName().Clone(b.f), originalConstraintNode, nil, nil)), result, b.f.NewKeywordTypeNode(ast.KindNeverKeyword), ) @@ -1635,7 +1635,7 @@ func (b *NodeBuilderImpl) createMappedTypeNodeFromType(t *Type) *ast.TypeNode { // just homomorphic ones. return b.f.NewConditionalTypeNode( b.typeToTypeNode(b.ch.getConstraintTypeFromMappedType(t)), - b.f.NewInferTypeNode(b.f.NewTypeParameterDeclaration(nil, newTypeVariable.AsTypeReferenceNode().TypeName.Clone(b.f), b.f.NewTypeOperatorNode(ast.KindKeyOfKeyword, b.typeToTypeNode(b.ch.getModifiersTypeFromMappedType(t))), nil, nil)), + b.f.NewInferTypeNode(b.f.NewTypeParameterDeclaration(nil, newTypeVariable.AsTypeReferenceNode().TypeName().Clone(b.f), b.f.NewTypeOperatorNode(ast.KindKeyOfKeyword, b.typeToTypeNode(b.ch.getModifiersTypeFromMappedType(t))), nil, nil)), result, b.f.NewKeywordTypeNode(ast.KindNeverKeyword), ) @@ -1774,7 +1774,7 @@ func (b *NodeBuilderImpl) parameterToParameterDeclarationName(parameterSymbol *a b.idToSymbol[cloned] = parameterSymbol return cloned case ast.KindQualifiedName: - cloned := b.f.DeepCloneNode(name.AsQualifiedName().Right) + cloned := b.f.DeepCloneNode(name.AsQualifiedName().Right()) b.e.SetEmitFlags(cloned, printer.EFNoAsciiEscaping) b.idToSymbol[cloned] = parameterSymbol return cloned @@ -1794,8 +1794,8 @@ func (b *NodeBuilderImpl) cloneBindingName(node *ast.Node) *ast.Node { bindingElement := visited.AsBindingElement() visited = b.f.UpdateBindingElement( bindingElement, - bindingElement.DotDotDotToken, - bindingElement.PropertyName, + bindingElement.DotDotDotToken(), + bindingElement.PropertyName(), bindingElement.Name(), nil, // remove initializer ) @@ -2487,7 +2487,7 @@ func (b *NodeBuilderImpl) isStringNamed(d *ast.Declaration) bool { return t.flags&TypeFlagsStringLike != 0 } if ast.IsElementAccessExpression(name) { - t := b.ch.checkExpression(name.AsElementAccessExpression().ArgumentExpression) + t := b.ch.checkExpression(name.AsElementAccessExpression().ArgumentExpression()) return t.flags&TypeFlagsStringLike != 0 } return ast.IsStringLiteral(name) @@ -2594,8 +2594,8 @@ func (b *NodeBuilderImpl) addPropertyToElementList(propertySymbol *ast.Symbol, t if b.ch.hasLateBindableName(decl) { if ast.IsBinaryExpression(decl) { name := ast.GetNameOfDeclaration(decl) - if name != nil && ast.IsElementAccessExpression(name) && ast.IsPropertyAccessEntityNameExpression(name.AsElementAccessExpression().ArgumentExpression, false /*allowJs*/) { - b.trackComputedName(name.AsElementAccessExpression().ArgumentExpression, saveEnclosingDeclaration) + if name != nil && ast.IsElementAccessExpression(name) && ast.IsPropertyAccessEntityNameExpression(name.AsElementAccessExpression().ArgumentExpression(), false /*allowJs*/) { + b.trackComputedName(name.AsElementAccessExpression().ArgumentExpression(), saveEnclosingDeclaration) } } else { b.trackComputedName(decl.Name().Expression(), saveEnclosingDeclaration) @@ -2848,7 +2848,7 @@ func (b *NodeBuilderImpl) createTypeNodeFromObjectType(t *Type) *ast.TypeNode { func getTypeAliasForTypeLiteral(c *Checker, t *Type) *ast.Symbol { if t.symbol != nil && t.symbol.Flags&ast.SymbolFlagsTypeLiteral != 0 && t.symbol.Declarations != nil { - node := ast.WalkUpParenthesizedTypes(t.symbol.Declarations[0].Parent) + node := ast.WalkUpParenthesizedTypes(t.symbol.Declarations[0].Parent()) if ast.IsTypeAliasDeclaration(node) { return c.getSymbolOfDeclaration(node) } @@ -2868,14 +2868,14 @@ func (b *NodeBuilderImpl) shouldWriteTypeOfFunctionSymbol(symbol *ast.Symbol, ty isNonLocalFunctionSymbol = true } else { for _, declaration := range symbol.Declarations { - if declaration.Parent.Kind == ast.KindSourceFile || declaration.Parent.Kind == ast.KindModuleBlock { + if declaration.Parent().Kind == ast.KindSourceFile || declaration.Parent().Kind == ast.KindModuleBlock { isNonLocalFunctionSymbol = true break } - if ast.IsFunctionExpressionOrArrowFunction(declaration) && ast.IsVariableDeclaration(declaration.Parent) && - ast.IsVariableDeclarationList(declaration.Parent.Parent) && ast.IsVariableStatement(declaration.Parent.Parent.Parent) && - declaration.Parent.Parent.Parent.Parent != nil && - (declaration.Parent.Parent.Parent.Parent.Kind == ast.KindSourceFile || declaration.Parent.Parent.Parent.Parent.Kind == ast.KindModuleBlock) { + if ast.IsFunctionExpressionOrArrowFunction(declaration) && ast.IsVariableDeclaration(declaration.Parent()) && + ast.IsVariableDeclarationList(declaration.Parent().Parent()) && ast.IsVariableStatement(declaration.Parent().Parent().Parent()) && + declaration.Parent().Parent().Parent().Parent() != nil && + (declaration.Parent().Parent().Parent().Parent().Kind == ast.KindSourceFile || declaration.Parent().Parent().Parent().Parent().Kind == ast.KindModuleBlock) { isNonLocalFunctionSymbol = true isFunctionExpressionSymbol = true break @@ -2884,8 +2884,8 @@ func (b *NodeBuilderImpl) shouldWriteTypeOfFunctionSymbol(symbol *ast.Symbol, ty } } if isStaticMethodSymbol || isNonLocalFunctionSymbol { - if isFunctionExpressionSymbol && symbol.ValueDeclaration != nil && symbol.ValueDeclaration.Parent != nil && symbol.ValueDeclaration.Parent != b.ctx.enclosingDeclaration { - symbol = b.ch.getMergedSymbol(symbol.ValueDeclaration.Parent.Symbol()) + if isFunctionExpressionSymbol && symbol.ValueDeclaration != nil && symbol.ValueDeclaration.Parent() != nil && symbol.ValueDeclaration.Parent() != b.ctx.enclosingDeclaration { + symbol = b.ch.getMergedSymbol(symbol.ValueDeclaration.Parent().Symbol()) } // typeof is allowed only for static/non local functions return (b.ctx.flags&nodebuilder.FlagsUseTypeOfFunction != 0 || b.ctx.visitedTypes.Has(typeId)) && // it is type of the symbol uses itself recursively @@ -2989,7 +2989,7 @@ func (b *NodeBuilderImpl) createAnonymousTypeNodeEx(t *Type, forceClassExpansion func (b *NodeBuilderImpl) getTypeFromTypeNode(node *ast.TypeNode, noMappedTypes bool) *Type { // !!! noMappedTypes optional param support - if node.Parent == nil { + if node.Parent() == nil { return b.ch.errorType } t := b.ch.getTypeFromTypeNode(node) @@ -3040,8 +3040,8 @@ func (b *NodeBuilderImpl) conditionalTypeToTypeNode(_t *Type) *ast.TypeNode { b.ctx.inferTypeParameters = t.root.inferTypeParameters extendsTypeNode := b.typeToTypeNode(b.ch.instantiateType(t.root.extendsType, newMapper)) b.ctx.inferTypeParameters = saveInferTypeParameters - trueTypeNode := b.typeToTypeNodeOrCircularityElision(b.ch.instantiateType(b.getTypeFromTypeNode(t.root.node.TrueType, false), newMapper)) - falseTypeNode := b.typeToTypeNodeOrCircularityElision(b.ch.instantiateType(b.getTypeFromTypeNode(t.root.node.FalseType, false), newMapper)) + trueTypeNode := b.typeToTypeNodeOrCircularityElision(b.ch.instantiateType(b.getTypeFromTypeNode(t.root.node.TrueType(), false), newMapper)) + falseTypeNode := b.typeToTypeNodeOrCircularityElision(b.ch.instantiateType(b.getTypeFromTypeNode(t.root.node.FalseType(), false), newMapper)) // outermost conditional makes `T` a type parameter, allowing the inner conditionals to be distributive // second conditional makes `T` have `T & checkType` substitution, so it is correctly usable as the checkType @@ -3053,7 +3053,7 @@ func (b *NodeBuilderImpl) conditionalTypeToTypeNode(_t *Type) *ast.TypeNode { // On the other hand, // checkType extends infer T extends checkType ? T extends extendsType ? trueType : falseType : never; // may also work with `infer ... extends ...` in, but would produce declarations only compatible with the latest TS. - newId := newTypeVariable.AsTypeReferenceNode().TypeName.AsIdentifier().Clone(b.f) + newId := newTypeVariable.AsTypeReferenceNode().TypeName().AsIdentifier().Clone(b.f) syntheticExtendsNode := b.f.NewInferTypeNode(b.f.NewTypeParameterDeclaration(nil, newId, nil, nil, nil)) innerCheckConditionalNode := b.f.NewConditionalTypeNode(newTypeVariable, extendsTypeNode, trueTypeNode, falseTypeNode) syntheticTrueNode := b.f.NewConditionalTypeNode(b.f.NewTypeReferenceNode(name.Clone(b.f), nil), b.f.DeepCloneNode(checkTypeNode), innerCheckConditionalNode, b.f.NewKeywordTypeNode(ast.KindNeverKeyword)) @@ -3075,7 +3075,7 @@ func (b *NodeBuilderImpl) getParentSymbolOfTypeParameter(typeParameter *TypePara // if ast.IsJSDocTemplateTag(tp.Parent) { // host = getEffectiveContainerForJSDocTemplateTag(tp.Parent) // } else { - host = tp.Parent + host = tp.Parent() // } if host == nil { return nil @@ -3429,7 +3429,7 @@ func (b *NodeBuilderImpl) typeToTypeNode(t *Type) *ast.TypeNode { // mutably update, node is freshly manufactured anyhow return b.f.NewIndexedAccessTypeNode(parentName, b.f.NewLiteralTypeNode(b.newStringLiteral(memberName))) } else if ast.IsTypeReferenceNode(parentName) { - return b.f.NewIndexedAccessTypeNode(b.f.NewTypeQueryNode(parentName.AsTypeReferenceNode().TypeName, nil), b.f.NewLiteralTypeNode(b.newStringLiteral(memberName))) + return b.f.NewIndexedAccessTypeNode(b.f.NewTypeQueryNode(parentName.AsTypeReferenceNode().TypeName(), nil), b.f.NewLiteralTypeNode(b.newStringLiteral(memberName))) } else { panic("Unhandled type node kind returned from `symbolToTypeNode`.") } @@ -3708,7 +3708,7 @@ func (b *NodeBuilderImpl) newIdentifier(text string, symbol *ast.Symbol) *ast.No func (b *NodeBuilderImpl) createAccessExpression(node *ast.Node) *ast.Expression { switch { case ast.IsQualifiedName(node): - return b.f.NewPropertyAccessExpression(b.createAccessExpression(node.AsQualifiedName().Left), nil /*questionDotToken*/, b.f.DeepCloneNode(node.AsQualifiedName().Right), ast.NodeFlagsNone) + return b.f.NewPropertyAccessExpression(b.createAccessExpression(node.AsQualifiedName().Left()), nil /*questionDotToken*/, b.f.DeepCloneNode(node.AsQualifiedName().Right()), ast.NodeFlagsNone) case ast.IsIdentifier(node), ast.IsPropertyAccessExpression(node), ast.IsExpressionWithTypeArguments(node): return b.f.DeepCloneNode(node) default: diff --git a/tsc/internal/checker/nodebuilderscopes.go b/tsc/internal/checker/nodebuilderscopes.go index 59b5fcd479b55..215ed8313475b 100644 --- a/tsc/internal/checker/nodebuilderscopes.go +++ b/tsc/internal/checker/nodebuilderscopes.go @@ -104,11 +104,11 @@ func (b *NodeBuilderImpl) enterNewScope(declaration *ast.Node, expandedParams [] existingFakeScope = b.ctx.enclosingDeclaration } } - if existingFakeScope == nil && b.ctx.enclosingDeclaration.Parent != nil { - if b.links.Has(b.ctx.enclosingDeclaration.Parent) { - links := b.links.Get(b.ctx.enclosingDeclaration.Parent) + if existingFakeScope == nil && b.ctx.enclosingDeclaration.Parent() != nil { + if b.links.Has(b.ctx.enclosingDeclaration.Parent()) { + links := b.links.Get(b.ctx.enclosingDeclaration.Parent()) if links.fakeScopeForSignatureDeclaration != nil && *links.fakeScopeForSignatureDeclaration == kind { - existingFakeScope = b.ctx.enclosingDeclaration.Parent + existingFakeScope = b.ctx.enclosingDeclaration.Parent() } } } @@ -141,9 +141,8 @@ func (b *NodeBuilderImpl) enterNewScope(declaration *ast.Node, expandedParams [] // has locals, and this is cheaper/easier than using a function-ish Node. fakeScope := b.f.NewBlock(b.f.NewNodeList([]*ast.Node{}), false) b.links.Get(fakeScope).fakeScopeForSignatureDeclaration = &kind - data := fakeScope.LocalsContainerData() - data.Locals = locals - fakeScope.Parent = b.ctx.enclosingDeclaration + ast.SetLocals(fakeScope, locals) + fakeScope.SetParent(b.ctx.enclosingDeclaration) b.ctx.enclosingDeclaration = fakeScope return nil } else { @@ -182,7 +181,7 @@ func (b *NodeBuilderImpl) enterNewScope(declaration *ast.Node, expandedParams [] var bindPattern func(e *ast.BindingPattern) bindPatternWorker := func(p *ast.BindingPattern) { - for _, e := range p.Elements.Nodes { + for _, e := range p.Elements().Nodes { switch e.Kind { case ast.KindOmittedExpression: return diff --git a/tsc/internal/checker/nodecopy.go b/tsc/internal/checker/nodecopy.go index 5b2a0739f7612..46dfdfeddd6a2 100644 --- a/tsc/internal/checker/nodecopy.go +++ b/tsc/internal/checker/nodecopy.go @@ -234,8 +234,8 @@ func (b *NodeBuilderImpl) tryReuseExistingNodeHelper(existing *ast.TypeNode) *as func (b *NodeBuilderImpl) getModuleSpecifierOverride(parent *ast.Node, lit *ast.Node) string { if b.ctx.enclosingFile != ast.GetSourceFileOfNode(lit) { mode := core.ResolutionModeNone - if parent.AsImportTypeNode().Attributes != nil { - mode, _ = parent.AsImportTypeNode().Attributes.AsImportAttributes().GetResolutionModeOverride(nil) + if parent.AsImportTypeNode().Attributes() != nil { + mode, _ = parent.AsImportTypeNode().Attributes().AsImportAttributes().GetResolutionModeOverride(nil) } name := lit.Text() originalName := name @@ -280,7 +280,7 @@ func (b *NodeBuilderImpl) rewriteModuleSpecifier(parent *ast.Node, lit *ast.Node func (b *NodeBuilderImpl) getEnclosingDeclarationIgnoringFakeScope() *ast.Node { enc := b.ctx.enclosingDeclaration for enc != nil && b.links.Get(enc).fakeScopeForSignatureDeclaration != nil { - enc = enc.Parent + enc = enc.Parent() } return enc } @@ -321,7 +321,7 @@ func getExistingNodeTreeVisitor(b *NodeBuilderImpl, bound *recoveryBoundary) *as } introducesError := false leftmost := ast.GetFirstIdentifier(node) - if ast.IsInJSFile(node) && (ast.IsExportsIdentifier(leftmost) || ast.IsModuleExportsAccessExpression(leftmost.Parent) || (ast.IsQualifiedName(leftmost.Parent) && ast.IsModuleIdentifier(leftmost.Parent.AsQualifiedName().Left) && ast.IsExportsIdentifier(leftmost.Parent.AsQualifiedName().Right))) { + if ast.IsInJSFile(node) && (ast.IsExportsIdentifier(leftmost) || ast.IsModuleExportsAccessExpression(leftmost.Parent()) || (ast.IsQualifiedName(leftmost.Parent()) && ast.IsModuleIdentifier(leftmost.Parent().AsQualifiedName().Left()) && ast.IsExportsIdentifier(leftmost.Parent().AsQualifiedName().Right()))) { introducesError = true return introducesError, b.setTextRange(b.f.DeepCloneNode(node), node), nil } @@ -383,33 +383,33 @@ func getExistingNodeTreeVisitor(b *NodeBuilderImpl, bound *recoveryBoundary) *as } var tryVisitSimpleTypeNode func(node *ast.Node) *ast.Node tryVisitIndexedAccess := func(node *ast.Node) *ast.Node { - resultObjectType := tryVisitSimpleTypeNode(node.AsIndexedAccessTypeNode().ObjectType) + resultObjectType := tryVisitSimpleTypeNode(node.AsIndexedAccessTypeNode().ObjectType()) if resultObjectType == nil { return nil } - return b.setTextRange(b.f.UpdateIndexedAccessTypeNode(node.AsIndexedAccessTypeNode(), resultObjectType, visitor.VisitNode(node.AsIndexedAccessTypeNode().IndexType)), node) + return b.setTextRange(b.f.UpdateIndexedAccessTypeNode(node.AsIndexedAccessTypeNode(), resultObjectType, visitor.VisitNode(node.AsIndexedAccessTypeNode().IndexType())), node) } tryVisitKeyOf := func(node *ast.Node) *ast.Node { to := node.AsTypeOperatorNode() - t := tryVisitSimpleTypeNode(to.Type) + t := tryVisitSimpleTypeNode(to.Type()) if t == nil { return nil } return b.setTextRange(b.f.UpdateTypeOperatorNode(to, to.Operator, t), node) } tryVisitTypeQuery := func(node *ast.Node) *ast.Node { - introducesError, exprName, _ := trackExistingEntityName(node.AsTypeQueryNode().ExprName, nil) + introducesError, exprName, _ := trackExistingEntityName(node.AsTypeQueryNode().ExprName(), nil) if !introducesError { return b.setTextRange(b.f.UpdateTypeQueryNode( node.AsTypeQueryNode(), exprName, - visitor.VisitNodes(node.AsTypeQueryNode().TypeArguments), + visitor.VisitNodes(node.AsTypeQueryNode().TypeArguments()), ), node) } - serializedName := b.serializeTypeName(node.AsTypeQueryNode().ExprName, true, visitor.VisitNodes(node.AsTypeQueryNode().TypeArguments)) + serializedName := b.serializeTypeName(node.AsTypeQueryNode().ExprName(), true, visitor.VisitNodes(node.AsTypeQueryNode().TypeArguments())) if serializedName != nil { - return b.setTextRange(serializedName, node.AsTypeQueryNode().ExprName) + return b.setTextRange(serializedName, node.AsTypeQueryNode().ExprName()) } return nil } @@ -433,18 +433,18 @@ func getExistingNodeTreeVisitor(b *NodeBuilderImpl, bound *recoveryBoundary) *as // in JS, should we enable that. return nil } - introducesError, newName, _ := trackExistingEntityName(node.AsTypeReferenceNode().TypeName, nil) + introducesError, newName, _ := trackExistingEntityName(node.AsTypeReferenceNode().TypeName(), nil) if !introducesError { - typeArguments := visitor.VisitNodes(node.AsTypeReferenceNode().TypeArguments) + typeArguments := visitor.VisitNodes(node.AsTypeReferenceNode().TypeArguments()) return b.setTextRange(b.f.UpdateTypeReferenceNode( node.AsTypeReferenceNode(), newName, typeArguments, ), node) } else { - serializedName := b.serializeTypeName(node.AsTypeReferenceNode().TypeName, false, visitor.VisitNodes(node.AsTypeReferenceNode().TypeArguments)) + serializedName := b.serializeTypeName(node.AsTypeReferenceNode().TypeName(), false, visitor.VisitNodes(node.AsTypeReferenceNode().TypeArguments())) if serializedName != nil { - return b.setTextRange(serializedName, node.AsTypeReferenceNode().TypeName) + return b.setTextRange(serializedName, node.AsTypeReferenceNode().TypeName()) } return nil } @@ -474,7 +474,7 @@ func getExistingNodeTreeVisitor(b *NodeBuilderImpl, bound *recoveryBoundary) *as // Begin JSDoc handling if node.Kind == ast.KindJSDocTypeExpression { // Unwrap JSDocTypeExpressions - return visitor.VisitNode(node.AsJSDocTypeExpression().Type) + return visitor.VisitNode(node.AsJSDocTypeExpression().Type()) } // !!! TODO: We don't _actually_ support jsdoc namepath types, emit `any` instead; verify we handle as gracefully as strada if node.Kind == ast.KindJSDocAllType /* || node.Kind == ast.JSDocNamepathType */ { @@ -486,24 +486,24 @@ func getExistingNodeTreeVisitor(b *NodeBuilderImpl, bound *recoveryBoundary) *as // } if node.Kind == ast.KindJSDocNullableType { unionMembers := []*ast.Node{ - visitor.VisitNode(node.AsJSDocNullableType().Type), + visitor.VisitNode(node.AsJSDocNullableType().Type()), factory.NewLiteralTypeNode(factory.NewKeywordExpression(ast.KindNullKeyword)), } return factory.NewUnionTypeNode(factory.NewNodeList(unionMembers)) } if node.Kind == ast.KindJSDocOptionalType { unionMembers := []*ast.Node{ - visitor.VisitNode(node.AsJSDocOptionalType().Type), + visitor.VisitNode(node.AsJSDocOptionalType().Type()), factory.NewKeywordTypeNode(ast.KindUndefinedKeyword), } return factory.NewUnionTypeNode(factory.NewNodeList(unionMembers)) } if node.Kind == ast.KindJSDocNonNullableType { // Unwrap - return visitor.VisitNode(node.AsJSDocNonNullableType().Type) + return visitor.VisitNode(node.AsJSDocNonNullableType().Type()) } if node.Kind == ast.KindJSDocVariadicType { // !!! TODO: verify this matches how jsdoc variadics are actually handled now? - return factory.NewArrayTypeNode(visitor.VisitNode(node.AsJSDocVariadicType().Type)) + return factory.NewArrayTypeNode(visitor.VisitNode(node.AsJSDocVariadicType().Type())) } if node.Kind == ast.KindJSDocTypeLiteral { var members []*ast.Node @@ -516,7 +516,7 @@ func getExistingNodeTreeVisitor(b *NodeBuilderImpl, bound *recoveryBoundary) *as if ast.IsIdentifier(n) { targetName = n } else { - targetName = n.AsQualifiedName().Right // !!! TODO: without typesystem backup, doing this cast unguarded seems really suspect, even though it is what strada does + targetName = n.AsQualifiedName().Right() // !!! TODO: without typesystem backup, doing this cast unguarded seems really suspect, even though it is what strada does } name := visitor.VisitNode(targetName) shouldBeOptional := t.AsJSDocParameterOrPropertyTag().IsBracketed || (t.TypeExpression() != nil && t.TypeExpression().Kind == ast.KindJSDocOptionalType) @@ -544,7 +544,7 @@ func getExistingNodeTreeVisitor(b *NodeBuilderImpl, bound *recoveryBoundary) *as // if node.Kind == ast.KindJSDocFunctionType {} // !!! no longer exists // End JSDoc handling - if ast.IsTypeReferenceNode(node) && ast.IsIdentifier(node.AsTypeReferenceNode().TypeName) && node.AsTypeReferenceNode().TypeName.AsIdentifier().Text == "" { + if ast.IsTypeReferenceNode(node) && ast.IsIdentifier(node.AsTypeReferenceNode().TypeName()) && node.AsTypeReferenceNode().TypeName().AsIdentifier().Text == "" { replacement := factory.NewKeywordTypeNode(ast.KindAnyKeyword) b.e.SetOriginal(replacement, node) return replacement @@ -563,9 +563,9 @@ func getExistingNodeTreeVisitor(b *NodeBuilderImpl, bound *recoveryBoundary) *as node.AsTypeParameterDeclaration(), visitor.VisitModifiers(node.Modifiers()), newName, - visitor.VisitNode(node.AsTypeParameterDeclaration().Constraint), - visitor.VisitNode(node.AsTypeParameterDeclaration().Expression), - visitor.VisitNode(node.AsTypeParameterDeclaration().DefaultType), + visitor.VisitNode(node.AsTypeParameterDeclaration().Constraint()), + visitor.VisitNode(node.AsTypeParameterDeclaration().Expression()), + visitor.VisitNode(node.AsTypeParameterDeclaration().DefaultType()), ) } if ast.IsIndexedAccessTypeNode(node) { @@ -593,7 +593,7 @@ func getExistingNodeTreeVisitor(b *NodeBuilderImpl, bound *recoveryBoundary) *as return node } if ast.IsTypeOperatorNode(node) { - if node.AsTypeOperatorNode().Operator == ast.KindUniqueKeyword && node.AsTypeOperatorNode().Type.Kind == ast.KindSymbolKeyword { + if node.AsTypeOperatorNode().Operator == ast.KindUniqueKeyword && node.AsTypeOperatorNode().Type().Kind == ast.KindSymbolKeyword { nonFakeEnclosing := b.getEnclosingDeclarationIgnoringFakeScope() sameScope := ast.FindAncestor(node, func(a *ast.Node) bool { return a == nonFakeEnclosing @@ -614,7 +614,7 @@ func getExistingNodeTreeVisitor(b *NodeBuilderImpl, bound *recoveryBoundary) *as if ast.IsLiteralImportTypeNode(node) { // assert keyword in imported attributes is deprecated, so we don't reuse types that contain it // Ex: import("pkg", { assert: {} } - if node.AsImportTypeNode().Attributes != nil && node.AsImportTypeNode().Attributes.AsImportAttributes().Token == ast.KindAssertKeyword { + if node.AsImportTypeNode().Attributes() != nil && node.AsImportTypeNode().Attributes().AsImportAttributes().Token == ast.KindAssertKeyword { bound.markError(nil) return node } @@ -627,12 +627,12 @@ func getExistingNodeTreeVisitor(b *NodeBuilderImpl, bound *recoveryBoundary) *as // !!! TODO: invalidate node reuse if js fallback logic used in type param list/typeof lookup (but isn't this logic gone?) // s := b.ch.symbolNodeLinks.Get(node).resolvedSymbol } - originalSpec := node.AsImportTypeNode().Argument.AsLiteralTypeNode().Literal + originalSpec := node.AsImportTypeNode().Argument().AsLiteralTypeNode().Literal() specifier := b.rewriteModuleSpecifier(node, originalSpec) if originalSpec == specifier { specifier = visitor.VisitNode(specifier) // visit node if not replaced } - arg := node.AsImportTypeNode().Argument + arg := node.AsImportTypeNode().Argument() if specifier != originalSpec { arg = factory.NewLiteralTypeNode(specifier) } @@ -640,9 +640,9 @@ func getExistingNodeTreeVisitor(b *NodeBuilderImpl, bound *recoveryBoundary) *as node.AsImportTypeNode(), node.AsImportTypeNode().IsTypeOf, arg, - visitor.VisitNode(node.AsImportTypeNode().Attributes), - visitor.VisitNode(node.AsImportTypeNode().Qualifier), - visitor.VisitNodes(node.AsImportTypeNode().TypeArguments), + visitor.VisitNode(node.AsImportTypeNode().Attributes()), + visitor.VisitNode(node.AsImportTypeNode().Qualifier()), + visitor.VisitNodes(node.AsImportTypeNode().TypeArguments()), ) } if node.Name() != nil && node.Name().Kind == ast.KindComputedPropertyName && !b.ch.hasLateBindableName(node) { @@ -652,7 +652,7 @@ func getExistingNodeTreeVisitor(b *NodeBuilderImpl, bound *recoveryBoundary) *as return visitor.VisitEachChild(node) } // !!! TODO: this condition matches strada, but it just seems wrong? Or at the very least extraordinarily approximate, and doesn't flag a builder error... - shouldRemoveDeclaration := !((b.ctx.internalFlags&nodebuilder.InternalFlagsAllowUnresolvedNames != 0) && ast.IsEntityNameExpression(node.Name().AsComputedPropertyName().Expression) && (b.ch.checkComputedPropertyName(node.Name()).flags&TypeFlagsAny != 0)) + shouldRemoveDeclaration := !((b.ctx.internalFlags&nodebuilder.InternalFlagsAllowUnresolvedNames != 0) && ast.IsEntityNameExpression(node.Name().AsComputedPropertyName().Expression()) && (b.ch.checkComputedPropertyName(node.Name()).flags&TypeFlagsAny != 0)) if shouldRemoveDeclaration { return nil } @@ -687,9 +687,9 @@ func getExistingNodeTreeVisitor(b *NodeBuilderImpl, bound *recoveryBoundary) *as return factory.UpdateParameterDeclaration( node.AsParameterDeclaration(), nil, - node.AsParameterDeclaration().DotDotDotToken, + node.AsParameterDeclaration().DotDotDotToken(), node.Name(), - node.AsParameterDeclaration().QuestionToken, + node.AsParameterDeclaration().QuestionToken(), newType, nil, ) @@ -698,58 +698,58 @@ func getExistingNodeTreeVisitor(b *NodeBuilderImpl, bound *recoveryBoundary) *as node.AsMethodSignatureDeclaration(), node.Modifiers(), node.Name(), - node.AsMethodSignatureDeclaration().PostfixToken, - node.AsMethodSignatureDeclaration().TypeParameters, - node.AsMethodSignatureDeclaration().Parameters, + node.AsMethodSignatureDeclaration().PostfixToken(), + node.AsMethodSignatureDeclaration().TypeParameters(), + node.AsMethodSignatureDeclaration().Parameters(), newType, ) case ast.KindCallSignature: return factory.UpdateCallSignatureDeclaration( node.AsCallSignatureDeclaration(), - node.AsCallSignatureDeclaration().TypeParameters, - node.AsCallSignatureDeclaration().Parameters, + node.AsCallSignatureDeclaration().TypeParameters(), + node.AsCallSignatureDeclaration().Parameters(), newType, ) case ast.KindJSDocSignature: return factory.UpdateJSDocSignature( node.AsJSDocSignature(), - node.AsJSDocSignature().TypeParameters, - node.AsJSDocSignature().Parameters, + node.AsJSDocSignature().TypeParameters(), + node.AsJSDocSignature().Parameters(), newType, ) case ast.KindConstructSignature: return factory.UpdateConstructSignatureDeclaration( node.AsConstructSignatureDeclaration(), - node.AsConstructSignatureDeclaration().TypeParameters, - node.AsConstructSignatureDeclaration().Parameters, + node.AsConstructSignatureDeclaration().TypeParameters(), + node.AsConstructSignatureDeclaration().Parameters(), newType, ) case ast.KindIndexSignature: return factory.UpdateIndexSignatureDeclaration( node.AsIndexSignatureDeclaration(), node.Modifiers(), - node.AsIndexSignatureDeclaration().Parameters, + node.AsIndexSignatureDeclaration().Parameters(), newType, ) case ast.KindFunctionType: return factory.UpdateFunctionTypeNode( node.AsFunctionTypeNode(), - node.AsFunctionTypeNode().TypeParameters, - node.AsFunctionTypeNode().Parameters, + node.AsFunctionTypeNode().TypeParameters(), + node.AsFunctionTypeNode().Parameters(), newType, ) case ast.KindConstructorType: return factory.UpdateConstructorTypeNode( node.AsConstructorTypeNode(), node.Modifiers(), - node.AsConstructorTypeNode().TypeParameters, - node.AsConstructorTypeNode().Parameters, + node.AsConstructorTypeNode().TypeParameters(), + node.AsConstructorTypeNode().Parameters(), newType, ) } } - if ast.IsComputedPropertyName(node) && ast.IsEntityNameExpression(node.AsComputedPropertyName().Expression) { - introducesError, result, _ := trackExistingEntityName(node.AsComputedPropertyName().Expression, nil) + if ast.IsComputedPropertyName(node) && ast.IsEntityNameExpression(node.AsComputedPropertyName().Expression()) { + introducesError, result, _ := trackExistingEntityName(node.AsComputedPropertyName().Expression(), nil) if !introducesError { return factory.UpdateComputedPropertyName(node.AsComputedPropertyName(), result) } else { @@ -761,8 +761,8 @@ func getExistingNodeTreeVisitor(b *NodeBuilderImpl, bound *recoveryBoundary) *as } if ast.IsTypePredicateNode(node) { var parameterName *ast.Node - if ast.IsIdentifier(node.AsTypePredicateNode().ParameterName) { - introducesError, result, _ := trackExistingEntityName(node.AsTypePredicateNode().ParameterName, nil) + if ast.IsIdentifier(node.AsTypePredicateNode().ParameterName()) { + introducesError, result, _ := trackExistingEntityName(node.AsTypePredicateNode().ParameterName(), nil) // Should not usually happen the only case is when a type predicate comes from a JSDoc type annotation with it's own parameter symbol definition. // /** @type {(v: unknown) => v is undefined} */ // const isUndef = v => v === undefined; @@ -771,22 +771,22 @@ func getExistingNodeTreeVisitor(b *NodeBuilderImpl, bound *recoveryBoundary) *as } parameterName = result } else { - parameterName = node.AsTypePredicateNode().ParameterName.Clone(factory) + parameterName = node.AsTypePredicateNode().ParameterName().Clone(factory) } return factory.UpdateTypePredicateNode( node.AsTypePredicateNode(), - visitor.VisitNode(node.AsTypePredicateNode().AssertsModifier), + visitor.VisitNode(node.AsTypePredicateNode().AssertsModifier()), parameterName, - visitor.VisitNode(node.AsTypePredicateNode().Type), + visitor.VisitNode(node.AsTypePredicateNode().Type()), ) } if ast.IsConditionalTypeNode(node) { - checkType := visitor.VisitNode(node.AsConditionalTypeNode().CheckType) + checkType := visitor.VisitNode(node.AsConditionalTypeNode().CheckType()) dispose := b.enterNewScope(node, nil, b.ch.getInferTypeParameters(node), nil, nil) - extendsType := visitor.VisitNode(node.AsConditionalTypeNode().ExtendsType) - trueType := visitor.VisitNode(node.AsConditionalTypeNode().TrueType) + extendsType := visitor.VisitNode(node.AsConditionalTypeNode().ExtendsType()) + trueType := visitor.VisitNode(node.AsConditionalTypeNode().TrueType()) dispose() - falseType := visitor.VisitNode(node.AsConditionalTypeNode().FalseType) + falseType := visitor.VisitNode(node.AsConditionalTypeNode().FalseType()) return factory.UpdateConditionalTypeNode( node.AsConditionalTypeNode(), checkType, @@ -842,7 +842,7 @@ func getExistingNodeTreeVisitor(b *NodeBuilderImpl, bound *recoveryBoundary) *as } else if ast.IsConditionalTypeNode(node) { // !!! TODO: impossible in combination with the scope start check??? typeParams = b.ch.getInferTypeParameters(node) } else if ast.IsMappedTypeNode(node) { - typeParams = []*Type{b.ch.getDeclaredTypeOfTypeParameter(b.ch.getSymbolOfDeclaration(node.AsMappedTypeNode().TypeParameter))} + typeParams = []*Type{b.ch.getDeclaredTypeOfTypeParameter(b.ch.getSymbolOfDeclaration(node.AsMappedTypeNode().TypeParameter()))} } exit = b.enterNewScope(node, params, typeParams, nil, nil) } diff --git a/tsc/internal/checker/pseudotypenodebuilder.go b/tsc/internal/checker/pseudotypenodebuilder.go index 9daf4b686fc43..f3612c5c0a312 100644 --- a/tsc/internal/checker/pseudotypenodebuilder.go +++ b/tsc/internal/checker/pseudotypenodebuilder.go @@ -57,8 +57,8 @@ func (b *NodeBuilderImpl) pseudoTypeToNode(t *pseudochecker.PseudoType) *ast.Nod for _, n := range errorNodes { b.ctx.tracker.ReportInferenceFallback(n) } - } else if ast.IsEntityNameExpression(node) && ast.IsDeclaration(node.Parent) { - b.ctx.tracker.ReportInferenceFallback(node.Parent) + } else if ast.IsEntityNameExpression(node) && ast.IsDeclaration(node.Parent()) { + b.ctx.tracker.ReportInferenceFallback(node.Parent()) } else { b.ctx.tracker.ReportInferenceFallback(node) } @@ -66,18 +66,18 @@ func (b *NodeBuilderImpl) pseudoTypeToNode(t *pseudochecker.PseudoType) *ast.Nod return b.serializeReturnTypeForSignature(b.ch.getSignatureFromDeclaration(node), false) } // use symbol type from parent declaration to automatically handle expression type widening without duplicating logic - if ast.IsReturnStatement(node.Parent) { + if ast.IsReturnStatement(node.Parent()) { enclosing := ast.GetContainingFunction(node) if ast.IsAccessor(enclosing) { return b.serializeTypeForDeclaration(enclosing, nil, nil, false) } return b.serializeReturnTypeForSignature(b.ch.getSignatureFromDeclaration(enclosing), false) } - if ast.IsArrowFunction(node.Parent) && node.Parent.AsArrowFunction().Body == node { - return b.serializeReturnTypeForSignature(b.ch.getSignatureFromDeclaration(node.Parent), false) + if ast.IsArrowFunction(node.Parent()) && node.Parent().AsArrowFunction().Body() == node { + return b.serializeReturnTypeForSignature(b.ch.getSignatureFromDeclaration(node.Parent()), false) } - if ast.IsDeclaration(node.Parent) { - return b.serializeTypeForDeclaration(node.Parent, nil, nil, false) + if ast.IsDeclaration(node.Parent()) { + return b.serializeTypeForDeclaration(node.Parent(), nil, nil, false) } // This might be effectively unreachable. If it's not, it may need more widening rules to mirror checker behavior for whatever expressions are serialized here ty := b.ch.getTypeOfExpression(node) @@ -118,7 +118,7 @@ func (b *NodeBuilderImpl) pseudoTypeToNode(t *pseudochecker.PseudoType) *ast.Nod var appendTypeNode func(node *ast.Node) appendTypeNode = func(node *ast.Node) { if ast.IsUnionTypeNode(node) { - for _, node := range node.AsUnionTypeNode().Types.Nodes { + for _, node := range node.AsUnionTypeNode().Types().Nodes { appendTypeNode(node) } return @@ -215,7 +215,7 @@ func (b *NodeBuilderImpl) pseudoTypeToNode(t *pseudochecker.PseudoType) *ast.Nod // something a true syntactic ID emitter couldn't possibly know (since the signature could // be from across files). This can't *really* happen in any cases ID doesn't already error on, though. // Just something to keep in mind if the ID checker keeps growing. - isConst := b.ch.isConstContext(elements[0].Name.Parent.Parent) + isConst := b.ch.isConstContext(elements[0].Name.Parent().Parent()) newElements := make([]*ast.Node, 0, len(elements)) // Member types are serialized within an object type literal, so set the @@ -302,7 +302,7 @@ func (b *NodeBuilderImpl) pseudoTypeToNode(t *pseudochecker.PseudoType) *ast.Nod ) } if b.ctx.enclosingFile == ast.GetSourceFileOfNode(e.Name) { - b.e.SetCommentRange(newProp, e.Name.Parent.Loc) + b.e.SetCommentRange(newProp, e.Name.Parent().Loc) } newElements = append(newElements, newProp) if cleanup != nil { @@ -345,12 +345,12 @@ func (b *NodeBuilderImpl) pseudoParameterToNode(p *pseudochecker.PseudoParameter nil, dotDotDot, // matches strada behavior of always reserializing param names from scratch - b.parameterToParameterDeclarationName(p.Name.Parent.Symbol(), p.Name.Parent), + b.parameterToParameterDeclarationName(p.Name.Parent().Symbol(), p.Name.Parent()), questionMark, b.pseudoTypeToNode(p.Type), nil, ) - if original := p.Name.Parent; ast.IsParameterDeclaration(original) { + if original := p.Name.Parent(); ast.IsParameterDeclaration(original) { b.setCommentRange(parameter, original) } return parameter @@ -432,7 +432,7 @@ func (b *NodeBuilderImpl) pseudoTypeEquivalentToType(t *pseudochecker.PseudoType } for _, e := range pt.Elements { var targetProp *ast.Symbol - elemSymbol := e.Name.Parent.Symbol() + elemSymbol := e.Name.Parent().Symbol() if elemSymbol != nil { targetProp = b.ch.getPropertyOfType(undefinedStripped, elemSymbol.Name) } @@ -447,7 +447,7 @@ func (b *NodeBuilderImpl) pseudoTypeEquivalentToType(t *pseudochecker.PseudoType } if targetProp == nil { if reportErrors { - b.ctx.tracker.ReportInferenceFallback(e.Name.Parent) + b.ctx.tracker.ReportInferenceFallback(e.Name.Parent()) } return false } @@ -455,7 +455,7 @@ func (b *NodeBuilderImpl) pseudoTypeEquivalentToType(t *pseudochecker.PseudoType targetIsOptional := targetProp.Flags&ast.SymbolFlagsOptional != 0 if e.Optional != targetIsOptional { if reportErrors { - b.ctx.tracker.ReportInferenceFallback(e.Name.Parent) + b.ctx.tracker.ReportInferenceFallback(e.Name.Parent()) } return false } @@ -472,7 +472,7 @@ func (b *NodeBuilderImpl) pseudoTypeEquivalentToType(t *pseudochecker.PseudoType b.ctx.tracker.ReportInferenceFallback(n) } } else if !isStructuralPseudoType(d.Type) { - b.ctx.tracker.ReportInferenceFallback(e.Name.Parent) + b.ctx.tracker.ReportInferenceFallback(e.Name.Parent()) } } return false @@ -484,7 +484,7 @@ func (b *NodeBuilderImpl) pseudoTypeEquivalentToType(t *pseudochecker.PseudoType // Target property type doesn't have a single call signature; can't validate continue } - paramEq := b.pseudoParametersEquivalentToParameters(d.Parameters, targetSig, reportErrors, e.Name.Parent) + paramEq := b.pseudoParametersEquivalentToParameters(d.Parameters, targetSig, reportErrors, e.Name.Parent()) if !paramEq { return false } @@ -492,13 +492,13 @@ func (b *NodeBuilderImpl) pseudoTypeEquivalentToType(t *pseudochecker.PseudoType if targetPredicate != nil { if !b.pseudoReturnTypeMatchesPredicate(d.ReturnType, targetPredicate) { if reportErrors { - b.ctx.tracker.ReportInferenceFallback(e.Name.Parent) + b.ctx.tracker.ReportInferenceFallback(e.Name.Parent()) } return false } } else if !b.pseudoTypeEquivalentToType(d.ReturnType, b.ch.getReturnTypeOfSignature(targetSig), false, false) { if reportErrors { - b.ctx.tracker.ReportInferenceFallback(e.Name.Parent) + b.ctx.tracker.ReportInferenceFallback(e.Name.Parent()) } return false } @@ -506,7 +506,7 @@ func (b *NodeBuilderImpl) pseudoTypeEquivalentToType(t *pseudochecker.PseudoType d := e.AsPseudoGetAccessor() if !b.pseudoTypeEquivalentToType(d.Type, propType, false, false) { if reportErrors { - b.ctx.tracker.ReportInferenceFallback(e.Name.Parent) + b.ctx.tracker.ReportInferenceFallback(e.Name.Parent()) } return false } @@ -515,7 +515,7 @@ func (b *NodeBuilderImpl) pseudoTypeEquivalentToType(t *pseudochecker.PseudoType writeType := b.ch.getWriteTypeOfSymbol(targetProp) if !b.pseudoTypeEquivalentToType(d.Parameter.Type, writeType, false, false) { if reportErrors { - b.ctx.tracker.ReportInferenceFallback(e.Name.Parent) + b.ctx.tracker.ReportInferenceFallback(e.Name.Parent()) } return false } @@ -593,7 +593,7 @@ func (b *NodeBuilderImpl) pseudoParametersEquivalentToParameters(params []*pseud paramType := b.ch.getTypeOfParameter(targetParam) if !b.pseudoTypeEquivalentToType(params[0].Type, paramType, params[0].Optional, false) { if reportErrors { - b.ctx.tracker.ReportInferenceFallback(params[0].Name.Parent) + b.ctx.tracker.ReportInferenceFallback(params[0].Name.Parent()) } return false } @@ -614,14 +614,14 @@ func (b *NodeBuilderImpl) pseudoParametersEquivalentToParameters(params []*pseud targetParam := targetSig.parameters[i] if p.Optional != b.ch.isOptionalParameter(targetParam.ValueDeclaration) { if reportErrors { - b.ctx.tracker.ReportInferenceFallback(p.Name.Parent) + b.ctx.tracker.ReportInferenceFallback(p.Name.Parent()) } return false } paramType := b.ch.getTypeOfParameter(targetParam) if !b.pseudoTypeEquivalentToType(p.Type, paramType, p.Optional, false) { if reportErrors { - b.ctx.tracker.ReportInferenceFallback(p.Name.Parent) + b.ctx.tracker.ReportInferenceFallback(p.Name.Parent()) } return false } @@ -652,35 +652,35 @@ func (b *NodeBuilderImpl) pseudoReturnTypeMatchesPredicate(rt *pseudochecker.Pse } tp := node.AsTypePredicateNode() // Check asserts modifier matches - isAsserts := tp.AssertsModifier != nil + isAsserts := tp.AssertsModifier() != nil predicateIsAsserts := predicate.kind == TypePredicateKindAssertsThis || predicate.kind == TypePredicateKindAssertsIdentifier if isAsserts != predicateIsAsserts { return false } // Check this vs identifier matches - isThis := ast.IsThisTypeNode(tp.ParameterName) + isThis := ast.IsThisTypeNode(tp.ParameterName()) predicateIsThis := predicate.kind == TypePredicateKindThis || predicate.kind == TypePredicateKindAssertsThis if isThis != predicateIsThis { return false } // For identifier predicates, check parameter name matches if !isThis { - if tp.ParameterName.Text() != predicate.parameterName { + if tp.ParameterName().Text() != predicate.parameterName { return false } } // Check the narrowed type, if any if predicate.t != nil { - if tp.Type == nil { + if tp.Type() == nil { return false } - predicateTypeFromNode := b.ch.getTypeFromTypeNode(tp.Type) + predicateTypeFromNode := b.ch.getTypeFromTypeNode(tp.Type()) if predicateTypeFromNode != predicate.t { if b.ch.compareTypesIdentical(predicateTypeFromNode, predicate.t) != TernaryTrue { return false } } - } else if tp.Type != nil { + } else if tp.Type() != nil { return false } return true diff --git a/tsc/internal/checker/relater.go b/tsc/internal/checker/relater.go index afb28721c8b9b..dd4e3b6f2073f 100644 --- a/tsc/internal/checker/relater.go +++ b/tsc/internal/checker/relater.go @@ -455,9 +455,9 @@ func (c *Checker) elaborateError(node *ast.Node, source *Type, target *Type, rel case ast.KindJsxExpression, ast.KindParenthesizedExpression: return c.elaborateError(node.Expression(), source, target, relation, headMessage, diagnosticOutput) case ast.KindBinaryExpression: - switch node.AsBinaryExpression().OperatorToken.Kind { + switch node.AsBinaryExpression().OperatorToken().Kind { case ast.KindEqualsToken, ast.KindCommaToken: - return c.elaborateError(node.AsBinaryExpression().Right, source, target, relation, headMessage, diagnosticOutput) + return c.elaborateError(node.AsBinaryExpression().Right(), source, target, relation, headMessage, diagnosticOutput) } case ast.KindObjectLiteralExpression: return c.elaborateObjectLiteral(node, source, target, relation, diagnosticOutput) @@ -2117,15 +2117,15 @@ func (c *Checker) typePredicateKindsMatch(a *TypePredicate, b *TypePredicate) bo func (c *Checker) createTypePredicateFromTypePredicateNode(node *ast.Node, signature *Signature) *TypePredicate { predicateNode := node.AsTypePredicateNode() var t *Type - if predicateNode.Type != nil { - t = c.getTypeFromTypeNode(predicateNode.Type) + if predicateNode.Type() != nil { + t = c.getTypeFromTypeNode(predicateNode.Type()) } - if ast.IsThisTypeNode(predicateNode.ParameterName) { - kind := core.IfElse(predicateNode.AssertsModifier != nil, TypePredicateKindAssertsThis, TypePredicateKindThis) + if ast.IsThisTypeNode(predicateNode.ParameterName()) { + kind := core.IfElse(predicateNode.AssertsModifier() != nil, TypePredicateKindAssertsThis, TypePredicateKindThis) return c.newTypePredicate(kind, "" /*parameterName*/, 0 /*parameterIndex*/, t) } - kind := core.IfElse(predicateNode.AssertsModifier != nil, TypePredicateKindAssertsIdentifier, TypePredicateKindIdentifier) - name := predicateNode.ParameterName.Text() + kind := core.IfElse(predicateNode.AssertsModifier() != nil, TypePredicateKindAssertsIdentifier, TypePredicateKindIdentifier) + name := predicateNode.ParameterName().Text() index := core.FindIndex(signature.parameters, func(p *ast.Symbol) bool { return p.Name == name }) return c.newTypePredicate(kind, name, int32(index), t) } @@ -2775,7 +2775,7 @@ func (r *Relater) hasExcessProperties(source *Type, target *Type, reportErrors b if r.errorNode == nil { panic("No errorNode in hasExcessProperties") } - if ast.IsJsxAttributes(r.errorNode) || ast.IsJsxOpeningLikeElement(r.errorNode) || ast.IsJsxOpeningLikeElement(r.errorNode.Parent) { + if ast.IsJsxAttributes(r.errorNode) || ast.IsJsxOpeningLikeElement(r.errorNode) || ast.IsJsxOpeningLikeElement(r.errorNode.Parent()) { // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. if prop.ValueDeclaration != nil && ast.IsJsxAttribute(prop.ValueDeclaration) && ast.GetSourceFileOfNode(r.errorNode) == ast.GetSourceFileOfNode(prop.ValueDeclaration.Name()) { @@ -2853,7 +2853,7 @@ func (c *Checker) getTypeOfPropertyInType(t *Type, name string) *Type { } func shouldCheckAsExcessProperty(prop *ast.Symbol, container *ast.Symbol) bool { - return prop.ValueDeclaration != nil && container.ValueDeclaration != nil && prop.ValueDeclaration.Parent == container.ValueDeclaration + return prop.ValueDeclaration != nil && container.ValueDeclaration != nil && prop.ValueDeclaration.Parent() == container.ValueDeclaration } func isIgnoredJsxProperty(source *Type, sourceProp *ast.Symbol) bool { @@ -3454,7 +3454,7 @@ func (r *Relater) structuredTypeRelatedToWorker(source *Type, target *Type, repo switch { case target.flags&TypeFlagsTypeParameter != 0: // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q]. - if source.objectFlags&ObjectFlagsMapped != 0 && source.AsMappedType().declaration.NameType == nil && r.isRelatedTo(r.c.getIndexType(target), r.c.getConstraintTypeFromMappedType(source), RecursionFlagsBoth, false) != TernaryFalse { + if source.objectFlags&ObjectFlagsMapped != 0 && source.AsMappedType().declaration.NameType() == nil && r.isRelatedTo(r.c.getIndexType(target), r.c.getConstraintTypeFromMappedType(source), RecursionFlagsBoth, false) != TernaryFalse { if getMappedTypeModifiers(source)&MappedTypeModifiersIncludeOptional == 0 { templateType := r.c.getTemplateTypeFromMappedType(source) indexedAccessType := r.c.getIndexedAccessType(target, r.c.getTypeParameterFromMappedType(source)) @@ -3624,7 +3624,7 @@ func (r *Relater) structuredTypeRelatedToWorker(source *Type, target *Type, repo } case r.c.isGenericMappedType(target) && r.relation != r.c.identityRelation: // Check if source type `S` is related to target type `{ [P in Q]: T }` or `{ [P in Q as R]: T}`. - keysRemapped := target.AsMappedType().declaration.NameType != nil + keysRemapped := target.AsMappedType().declaration.NameType() != nil templateType := r.c.getTemplateTypeFromMappedType(target) modifiers := getMappedTypeModifiers(target) if modifiers&MappedTypeModifiersExcludeOptional == 0 { @@ -5024,7 +5024,7 @@ func (c *Checker) isTypeDerivedFrom(source *Type, target *Type) bool { } func (c *Checker) isDistributionDependent(root *ConditionalRoot) bool { - return root.isDistributive && (c.isTypeParameterPossiblyReferenced(root.checkType, root.node.TrueType) || c.isTypeParameterPossiblyReferenced(root.checkType, root.node.FalseType)) + return root.isDistributive && (c.isTypeParameterPossiblyReferenced(root.checkType, root.node.TrueType()) || c.isTypeParameterPossiblyReferenced(root.checkType, root.node.FalseType())) } func (r *Relater) traceUnionsOrIntersectionsTooLarge(source *Type, target *Type) { diff --git a/tsc/internal/checker/services.go b/tsc/internal/checker/services.go index 73d70a79293c7..f6b8d04726609 100644 --- a/tsc/internal/checker/services.go +++ b/tsc/internal/checker/services.go @@ -65,11 +65,11 @@ func (c *Checker) getSymbolsInScope(location *ast.Node, meaning ast.SymbolFlags) var lastLocation *ast.Node for location != nil { if ast.IsModuleDeclaration(location) && - location.AsModuleDeclaration().Attributes != nil && - lastLocation == location.AsModuleDeclaration().Attributes { + location.AsModuleDeclaration().Attributes() != nil && + lastLocation == location.AsModuleDeclaration().Attributes() { // Module declaration is not in scope inside its attributes. lastLocation = location - location = location.Parent + location = location.Parent() continue } @@ -116,7 +116,7 @@ func (c *Checker) getSymbolsInScope(location *ast.Node, meaning ast.SymbolFlags) isStaticSymbol = ast.IsStatic(location) lastLocation = location - location = location.Parent + location = location.Parent() } copySymbols(c.globals, meaning) @@ -170,7 +170,7 @@ func (c *Checker) isValidPropertyAccess(node *ast.Node, propertyName string) boo case ast.KindPropertyAccessExpression: return c.isValidPropertyAccessWithType(node, node.Expression().Kind == ast.KindSuperKeyword, propertyName, c.getWidenedType(c.checkExpression(node.Expression()))) case ast.KindQualifiedName: - return c.isValidPropertyAccessWithType(node, false /*isSuper*/, propertyName, c.getWidenedType(c.checkExpression(node.AsQualifiedName().Left))) + return c.isValidPropertyAccessWithType(node, false /*isSuper*/, propertyName, c.getWidenedType(c.checkExpression(node.AsQualifiedName().Left()))) case ast.KindImportType: return c.isValidPropertyAccessWithType(node, false /*isSuper*/, propertyName, c.getTypeFromTypeNode(node)) } @@ -336,7 +336,7 @@ func (c *Checker) runWithInferenceBlockedFromSourceNode[T any](node *ast.Node, f toMarkSkip := node for { c.skipDirectInferenceNodes.Add(toMarkSkip) - toMarkSkip = toMarkSkip.Parent + toMarkSkip = toMarkSkip.Parent() if toMarkSkip == nil || toMarkSkip == containingCall { break } @@ -378,7 +378,7 @@ func (c *Checker) runWithoutResolvedSignatureCaching[T any](node *ast.Node, fn f cachedTypes[symbolLinks] = resolvedType symbolLinks.resolvedType = nil } - ancestorNode = ast.FindAncestor(ancestorNode.Parent, ast.IsCallLikeOrFunctionLikeExpression) + ancestorNode = ast.FindAncestor(ancestorNode.Parent(), ast.IsCallLikeOrFunctionLikeExpression) } result := fn() for signatureLinks, resolvedSignature := range cachedResolvedSignatures { @@ -476,8 +476,8 @@ func (c *Checker) GetExportSpecifierLocalTargetSymbol(node *ast.Node) *ast.Symbo // node should be ExportSpecifier | Identifier switch node.Kind { case ast.KindExportSpecifier: - if node.Parent.Parent.ModuleSpecifier() != nil { - return c.getExternalModuleMember(node.Parent.Parent, node, false /*dontResolveAlias*/) + if node.Parent().Parent().ModuleSpecifier() != nil { + return c.getExternalModuleMember(node.Parent().Parent(), node, false /*dontResolveAlias*/) } name := node.PropertyNameOrName() if name.Kind == ast.KindStringLiteral { @@ -505,8 +505,8 @@ func (c *Checker) GetShorthandAssignmentValueSymbol(location *ast.Node) *ast.Sym * @return a tuple of two symbols */ func (c *Checker) GetSymbolsOfParameterPropertyDeclaration(parameter *ast.Node /*ParameterPropertyDeclaration*/, parameterName string) (*ast.Symbol, *ast.Symbol) { - constructorDeclaration := parameter.Parent - classDeclaration := parameter.Parent.Parent + constructorDeclaration := parameter.Parent() + classDeclaration := parameter.Parent().Parent() parameterSymbol := c.getSymbol(constructorDeclaration.Locals(), parameterName, ast.SymbolFlagsValue) propertySymbol := c.getSymbol(c.getMembersOfSymbol(classDeclaration.Symbol()), parameterName, ast.SymbolFlagsValue) @@ -566,14 +566,14 @@ func (c *Checker) IsSymbolReferencedInFile( if refSymbol == symbol { return true } - if token.Parent != nil && token.Parent.Kind == ast.KindShorthandPropertyAssignment { - shorthandSymbol := c.GetShorthandAssignmentValueSymbol(token.Parent) + if token.Parent() != nil && token.Parent().Kind == ast.KindShorthandPropertyAssignment { + shorthandSymbol := c.GetShorthandAssignmentValueSymbol(token.Parent()) if shorthandSymbol == symbol { return true } } - if token.Parent != nil && ast.IsExportSpecifier(token.Parent) { - localSymbol := c.getLocalSymbolForExportSpecifier(token.AsIdentifier(), refSymbol, token.Parent.AsExportSpecifier()) + if token.Parent() != nil && ast.IsExportSpecifier(token.Parent()) { + localSymbol := c.getLocalSymbolForExportSpecifier(token.AsIdentifier(), refSymbol, token.Parent().AsExportSpecifier()) if localSymbol == symbol { return true } @@ -602,15 +602,15 @@ func (c *Checker) GetReferencesToSymbolInFile( result = append(result, token) continue } - if token.Parent != nil && token.Parent.Kind == ast.KindShorthandPropertyAssignment { - shorthandSymbol := c.GetShorthandAssignmentValueSymbol(token.Parent) + if token.Parent() != nil && token.Parent().Kind == ast.KindShorthandPropertyAssignment { + shorthandSymbol := c.GetShorthandAssignmentValueSymbol(token.Parent()) if shorthandSymbol == symbol { result = append(result, token) continue } } - if token.Parent != nil && ast.IsExportSpecifier(token.Parent) { - localSymbol := c.getLocalSymbolForExportSpecifier(token.AsIdentifier(), refSymbol, token.Parent.AsExportSpecifier()) + if token.Parent() != nil && ast.IsExportSpecifier(token.Parent()) { + localSymbol := c.getLocalSymbolForExportSpecifier(token.AsIdentifier(), refSymbol, token.Parent().AsExportSpecifier()) if localSymbol == symbol { result = append(result, token) continue @@ -630,15 +630,15 @@ func (c *Checker) getLocalSymbolForExportSpecifier(referenceLocation *ast.Identi } func isExportSpecifierAlias(referenceLocation *ast.Identifier, exportSpecifier *ast.ExportSpecifier) bool { - debug.Assert(exportSpecifier.PropertyName == referenceLocation.AsNode() || exportSpecifier.Name() == referenceLocation.AsNode(), "referenceLocation is not export specifier name or property name") - propertyName := exportSpecifier.PropertyName + debug.Assert(exportSpecifier.PropertyName() == referenceLocation.AsNode() || exportSpecifier.Name() == referenceLocation.AsNode(), "referenceLocation is not export specifier name or property name") + propertyName := exportSpecifier.PropertyName() if propertyName != nil { // Given `export { foo as bar } [from "someModule"]`: It's an alias at `foo`, but at `bar` it's a new symbol. return propertyName == referenceLocation.AsNode() } 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.ModuleSpecifier() == nil + return exportSpecifier.Parent().Parent().ModuleSpecifier() == nil } } @@ -716,7 +716,7 @@ func (c *Checker) getUninstantiatedSignatures(node *ast.Node) []*Signature { } return c.getSignaturesOfType(c.getTypeOfExpression(node.TagName()), SignatureKindCall) case ast.KindTaggedTemplateExpression: - return c.getSignaturesOfType(c.getTypeOfExpression(node.AsTaggedTemplateExpression().Tag), SignatureKindCall) + return c.getSignaturesOfType(c.getTypeOfExpression(node.AsTaggedTemplateExpression().Tag()), SignatureKindCall) case ast.KindBinaryExpression, ast.KindJsxOpeningFragment: return nil } @@ -740,8 +740,8 @@ func (c *Checker) getTypeParameterConstraintForPositionAcrossSignatures(signatur func (c *Checker) getTypeArgumentConstraint(node *ast.Node) *Type { var typeArgumentPosition int = -1 - if ast.HasTypeArguments(node.Parent) { - typeArgs := node.Parent.TypeArguments() + if ast.HasTypeArguments(node.Parent()) { + typeArgs := node.Parent().TypeArguments() for i, arg := range typeArgs { if arg == node { typeArgumentPosition = i @@ -754,22 +754,22 @@ func (c *Checker) getTypeArgumentConstraint(node *ast.Node) *Type { // The node could be a type argument of a call, a `new` expression, a decorator, an // instantiation expression, or a generic type instantiation. - if ast.IsCallLikeExpression(node.Parent) { + if ast.IsCallLikeExpression(node.Parent()) { return c.getTypeParameterConstraintForPositionAcrossSignatures( - c.getUninstantiatedSignatures(node.Parent), + c.getUninstantiatedSignatures(node.Parent()), typeArgumentPosition, ) } - if ast.IsDecorator(node.Parent.Parent) { + if ast.IsDecorator(node.Parent().Parent()) { return c.getTypeParameterConstraintForPositionAcrossSignatures( - c.getUninstantiatedSignatures(node.Parent.Parent), + c.getUninstantiatedSignatures(node.Parent().Parent()), typeArgumentPosition, ) } - if ast.IsExpressionWithTypeArguments(node.Parent) && ast.IsExpressionStatement(node.Parent.Parent) { - uninstantiatedType := c.checkExpression(node.Parent.Expression()) + if ast.IsExpressionWithTypeArguments(node.Parent()) && ast.IsExpressionStatement(node.Parent().Parent()) { + uninstantiatedType := c.checkExpression(node.Parent().Expression()) callConstraint := c.getTypeParameterConstraintForPositionAcrossSignatures( c.getSignaturesOfType(uninstantiatedType, SignatureKindCall), @@ -791,8 +791,8 @@ func (c *Checker) getTypeArgumentConstraint(node *ast.Node) *Type { return c.getIntersectionType([]*Type{callConstraint, constructConstraint}) } - if ast.IsTypeReferenceType(node.Parent) { - typeParameters := c.getTypeParametersForTypeReferenceOrImport(node.Parent) + if ast.IsTypeReferenceType(node.Parent()) { + typeParameters := c.getTypeParametersForTypeReferenceOrImport(node.Parent()) if len(typeParameters) == 0 { return nil } @@ -804,7 +804,7 @@ func (c *Checker) getTypeArgumentConstraint(node *ast.Node) *Type { if constraint != nil { return c.instantiateType( constraint, - newTypeMapper(typeParameters, c.getEffectiveTypeArguments(node.Parent, typeParameters)), + newTypeMapper(typeParameters, c.getEffectiveTypeArguments(node.Parent(), typeParameters)), ) } } @@ -887,7 +887,7 @@ func (c *Checker) GetConstantValue(node *ast.Node) any { if symbol != nil && symbol.Flags&ast.SymbolFlagsEnumMember != 0 { // inline property\index accesses only for const enums member := symbol.ValueDeclaration - if ast.IsEnumConst(member.Parent) { + if ast.IsEnumConst(member.Parent()) { return c.getEnumMemberValue(member).Value } } @@ -1033,9 +1033,9 @@ func (c *Checker) GetPropertySymbolsFromContextualType(node *ast.Node, contextua return nil } filteredTypes := contextualType.Types() - if ast.IsObjectLiteralExpression(node.Parent) || ast.IsJsxAttributes(node.Parent) { + if ast.IsObjectLiteralExpression(node.Parent()) || ast.IsJsxAttributes(node.Parent()) { filteredTypes = core.Filter(filteredTypes, func(t *Type) bool { - return !c.IsTypeInvalidDueToUnionDiscriminant(t, node.Parent) + return !c.IsTypeInvalidDueToUnionDiscriminant(t, node.Parent()) }) } discriminatedPropertySymbols := core.MapNonNil(filteredTypes, func(t *Type) *ast.Symbol { @@ -1067,9 +1067,9 @@ func (c *Checker) GetPropertySymbolsFromContextualType(node *ast.Node, contextua // // [a] = [ property1, property2 ] func (c *Checker) GetPropertySymbolOfDestructuringAssignment(location *ast.Node) *ast.Symbol { - if ast.IsArrayLiteralOrObjectLiteralDestructuringPattern(location.Parent.Parent) { + if ast.IsArrayLiteralOrObjectLiteralDestructuringPattern(location.Parent().Parent()) { // Get the type of the object or array literal and then look for property of given name in the type - if typeOfObjectLiteral := c.getTypeOfAssignmentPattern(location.Parent.Parent); typeOfObjectLiteral != nil { + if typeOfObjectLiteral := c.getTypeOfAssignmentPattern(location.Parent().Parent()); typeOfObjectLiteral != nil { return c.getPropertyOfType(typeOfObjectLiteral, location.Text()) } } @@ -1089,29 +1089,29 @@ func (c *Checker) getTypeOfAssignmentPattern(expr *ast.Node) *Type { // If this is from "for of" // for ( { a } of elems) { // } - if ast.IsForOfStatement(expr.Parent) { - iteratedType := c.checkRightHandSideOfForOf(expr.Parent) + if ast.IsForOfStatement(expr.Parent()) { + iteratedType := c.checkRightHandSideOfForOf(expr.Parent()) return c.checkDestructuringAssignment(expr, core.OrElse(iteratedType, c.errorType), CheckModeNormal, false) } // If this is from "for" initializer // for ({a } = elems[0];.....) { } - if ast.IsBinaryExpression(expr.Parent) { - iteratedType := c.getTypeOfExpression(expr.Parent.AsBinaryExpression().Right) + if ast.IsBinaryExpression(expr.Parent()) { + iteratedType := c.getTypeOfExpression(expr.Parent().AsBinaryExpression().Right()) return c.checkDestructuringAssignment(expr, core.OrElse(iteratedType, c.errorType), CheckModeNormal, false) } // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if ast.IsPropertyAssignment(expr.Parent) { - node := expr.Parent.Parent + if ast.IsPropertyAssignment(expr.Parent()) { + node := expr.Parent().Parent() typeOfParentObjectLiteral := core.OrElse(c.getTypeOfAssignmentPattern(node), c.errorType) - propertyIndex := slices.Index(node.Properties(), expr.Parent) + propertyIndex := slices.Index(node.Properties(), expr.Parent()) return c.checkObjectLiteralDestructuringPropertyAssignment(node, typeOfParentObjectLiteral, propertyIndex, nil, false) } // Array literal assignment - array destructuring pattern - node := expr.Parent + node := expr.Parent() // [{ 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) + elementType := core.OrElse(c.checkIteratedTypeOrElementType(IterationUseDestructuring, typeOfArrayLiteral, c.undefinedType, expr.Parent()), c.errorType) return c.checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, slices.Index(node.Elements(), expr), elementType, CheckModeNormal) } diff --git a/tsc/internal/checker/symbolaccessibility.go b/tsc/internal/checker/symbolaccessibility.go index 6115adea5d373..a8a16698bbf04 100644 --- a/tsc/internal/checker/symbolaccessibility.go +++ b/tsc/internal/checker/symbolaccessibility.go @@ -234,14 +234,14 @@ func (c *Checker) getVariableDeclarationOfObjectLiteral(symbol *ast.Symbol, mean return nil } firstDecl := symbol.Declarations[0] - if firstDecl.Parent == nil { + if firstDecl.Parent() == nil { return nil } - if !ast.IsVariableDeclaration(firstDecl.Parent) { + if !ast.IsVariableDeclaration(firstDecl.Parent()) { return nil } - if ast.IsObjectLiteralExpression(firstDecl) && firstDecl == firstDecl.Parent.Initializer() || ast.IsTypeLiteralNode(firstDecl) && firstDecl == firstDecl.Parent.Type() { - return c.getSymbolOfDeclaration(firstDecl.Parent) + if ast.IsObjectLiteralExpression(firstDecl) && firstDecl == firstDecl.Parent().Initializer() || ast.IsTypeLiteralNode(firstDecl) && firstDecl == firstDecl.Parent().Type() { + return c.getSymbolOfDeclaration(firstDecl.Parent()) } return nil } @@ -285,34 +285,34 @@ func (c *Checker) getContainersOfSymbol(symbol *ast.Symbol, enclosingDeclaration } var candidates []*ast.Symbol for _, d := range symbol.Declarations { - if !ast.IsAmbientModule(d) && d.Parent != nil { + if !ast.IsAmbientModule(d) && d.Parent() != nil { // direct children of a module - if hasNonGlobalAugmentationExternalModuleSymbol(d.Parent) { - sym := c.getSymbolOfDeclaration(d.Parent) + if hasNonGlobalAugmentationExternalModuleSymbol(d.Parent()) { + sym := c.getSymbolOfDeclaration(d.Parent()) if sym != nil && !slices.Contains(candidates, sym) { candidates = append(candidates, sym) } continue } // export ='d member of an ambient module - if ast.IsModuleBlock(d.Parent) && d.Parent.Parent != nil && c.resolveExternalModuleSymbol(c.getSymbolOfDeclaration(d.Parent.Parent), false) == symbol { - sym := c.getSymbolOfDeclaration(d.Parent.Parent) + if ast.IsModuleBlock(d.Parent()) && d.Parent().Parent() != nil && c.resolveExternalModuleSymbol(c.getSymbolOfDeclaration(d.Parent().Parent()), false) == symbol { + sym := c.getSymbolOfDeclaration(d.Parent().Parent()) if sym != nil && !slices.Contains(candidates, sym) { candidates = append(candidates, sym) } continue } } - if ast.IsClassExpression(d) && ast.IsBinaryExpression(d.Parent) && d.Parent.AsBinaryExpression().OperatorToken.Kind == ast.KindEqualsToken && ast.IsAccessExpression(d.Parent.AsBinaryExpression().Left) && ast.IsEntityNameExpression(d.Parent.AsBinaryExpression().Left.Expression()) { - if ast.IsModuleExportsAccessExpression(d.Parent.AsBinaryExpression().Left) || ast.IsExportsIdentifier(d.Parent.AsBinaryExpression().Left.Expression()) { + if ast.IsClassExpression(d) && ast.IsBinaryExpression(d.Parent()) && d.Parent().AsBinaryExpression().OperatorToken().Kind == ast.KindEqualsToken && ast.IsAccessExpression(d.Parent().AsBinaryExpression().Left()) && ast.IsEntityNameExpression(d.Parent().AsBinaryExpression().Left().Expression()) { + if ast.IsModuleExportsAccessExpression(d.Parent().AsBinaryExpression().Left()) || ast.IsExportsIdentifier(d.Parent().AsBinaryExpression().Left().Expression()) { sym := c.getSymbolOfDeclaration(ast.GetSourceFileOfNode(d).AsNode()) if sym != nil && !slices.Contains(candidates, sym) { candidates = append(candidates, sym) } continue } - c.checkExpressionCached(d.Parent.AsBinaryExpression().Left.Expression()) - sym := c.symbolNodeLinks.Get(d.Parent.AsBinaryExpression().Left.Expression()).resolvedSymbol + c.checkExpressionCached(d.Parent().AsBinaryExpression().Left().Expression()) + sym := c.symbolNodeLinks.Get(d.Parent().AsBinaryExpression().Left().Expression()).resolvedSymbol if sym != nil && !slices.Contains(candidates, sym) { candidates = append(candidates, sym) } @@ -614,7 +614,7 @@ func isUMDExportSymbol(symbol *ast.Symbol) bool { } func isNamespaceReexportDeclaration(node *ast.Node) bool { - return ast.IsNamespaceExport(node) && node.Parent.ModuleSpecifier() != nil + return ast.IsNamespaceExport(node) && node.Parent().ModuleSpecifier() != nil } func (c *Checker) getCandidateListForSymbol( @@ -758,7 +758,7 @@ func (c *Checker) someSymbolTableInScope( enclosingDeclaration *ast.Node, callback func(symbolTable ast.SymbolTable, tableId symbolTableID, ignoreQualification bool, isLocalNameLookup bool, scopeNode *ast.Node) bool, ) bool { - for location := enclosingDeclaration; location != nil; location = location.Parent { + for location := enclosingDeclaration; location != nil; location = location.Parent() { // Locals of a source file are not in scope (because they get merged into the global symbol table) if canHaveLocals(location) && location.Locals() != nil && !ast.IsGlobalSourceFile(location) { if callback(location.Locals(), symbolTableIDFromLocals(location.AsNode()), false, true, location) { diff --git a/tsc/internal/checker/utilities.go b/tsc/internal/checker/utilities.go index 82071d2dde43d..09c972d090a72 100644 --- a/tsc/internal/checker/utilities.go +++ b/tsc/internal/checker/utilities.go @@ -93,7 +93,7 @@ func getAssignmentTargetKind(node *ast.Node) AssignmentKind { } switch target.Kind { case ast.KindBinaryExpression: - binaryOperator := target.AsBinaryExpression().OperatorToken.Kind + binaryOperator := target.AsBinaryExpression().OperatorToken().Kind if binaryOperator == ast.KindEqualsToken || ast.IsLogicalOrCoalescingAssignmentOperator(binaryOperator) { return AssignmentKindDefinite } @@ -110,7 +110,7 @@ func isDeleteTarget(node *ast.Node) bool { if !ast.IsAccessExpression(node) { return false } - node = ast.WalkUpParenthesizedExpressions(node.Parent) + node = ast.WalkUpParenthesizedExpressions(node.Parent()) return node != nil && node.Kind == ast.KindDeleteExpression } @@ -120,20 +120,20 @@ func isInCompoundLikeAssignment(node *ast.Node) bool { } func isCompoundLikeAssignment(assignment *ast.Node) bool { - right := ast.SkipParentheses(assignment.AsBinaryExpression().Right) - return right.Kind == ast.KindBinaryExpression && isShiftOperatorOrHigher(right.AsBinaryExpression().OperatorToken.Kind) + right := ast.SkipParentheses(assignment.AsBinaryExpression().Right()) + return right.Kind == ast.KindBinaryExpression && isShiftOperatorOrHigher(right.AsBinaryExpression().OperatorToken().Kind) } func isConstTypeReference(node *ast.Node) bool { - return ast.IsTypeReferenceNode(node) && len(node.TypeArguments()) == 0 && ast.IsIdentifier(node.AsTypeReferenceNode().TypeName) && node.AsTypeReferenceNode().TypeName.Text() == "const" + return ast.IsTypeReferenceNode(node) && len(node.TypeArguments()) == 0 && ast.IsIdentifier(node.AsTypeReferenceNode().TypeName()) && node.AsTypeReferenceNode().TypeName().Text() == "const" } // isConstTypeReferenceName reports whether node is the `const` type name of a `const` // assertion (`x as const` / `x`), which must not be resolved as a real name. func isConstTypeReferenceName(node *ast.Node) bool { return node != nil && ast.IsIdentifier(node) && - node.Parent != nil && isConstTypeReference(node.Parent) && - node.Parent.Parent != nil && ast.IsAssertionExpression(node.Parent.Parent) + node.Parent() != nil && isConstTypeReference(node.Parent()) && + node.Parent().Parent() != nil && ast.IsAssertionExpression(node.Parent().Parent()) } // isExportAssignmentExpressionName reports whether node is (the root entity name of) the @@ -145,24 +145,24 @@ func isExportAssignmentExpressionName(node *ast.Node) bool { return false } current := node - for current.Parent != nil && ast.IsPropertyAccessOrQualifiedName(current.Parent) { - current = current.Parent + for current.Parent() != nil && ast.IsPropertyAccessOrQualifiedName(current.Parent()) { + current = current.Parent() } - return current.Parent != nil && ast.IsExportAssignment(current.Parent) && current.Parent.Expression() == current + return current.Parent() != nil && ast.IsExportAssignment(current.Parent()) && current.Parent().Expression() == current } func GetSingleVariableOfVariableStatement(node *ast.Node) *ast.Node { if !ast.IsVariableStatement(node) { return nil } - return core.FirstOrNil(node.AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes) + return core.FirstOrNil(node.AsVariableStatement().DeclarationList().AsVariableDeclarationList().Declarations().Nodes) } func isTypeReferenceIdentifier(node *ast.Node) bool { - for node.Parent.Kind == ast.KindQualifiedName { - node = node.Parent + for node.Parent().Kind == ast.KindQualifiedName { + node = node.Parent() } - return ast.IsTypeReferenceNode(node.Parent) + return ast.IsTypeReferenceNode(node.Parent()) } func IsInTypeQuery(node *ast.Node) bool { @@ -204,12 +204,12 @@ func isShorthandAmbientModule(node *ast.Node) bool { } func getAliasDeclarationFromName(node *ast.Node) *ast.Node { - switch node.Parent.Kind { + switch node.Parent().Kind { case ast.KindImportClause, ast.KindImportSpecifier, ast.KindNamespaceImport, ast.KindExportSpecifier, ast.KindExportAssignment, ast.KindImportEqualsDeclaration, ast.KindNamespaceExport: - return node.Parent + return node.Parent() case ast.KindQualifiedName: - return getAliasDeclarationFromName(node.Parent) + return getAliasDeclarationFromName(node.Parent()) } return nil } @@ -219,8 +219,8 @@ func entityNameToString(name *ast.Node) string { } func getContainingQualifiedNameNode(node *ast.Node) *ast.Node { - for ast.IsQualifiedName(node.Parent) { - node = node.Parent + for ast.IsQualifiedName(node.Parent()) { + node = node.Parent() } return node } @@ -238,12 +238,12 @@ func getExternalModuleRequireArgument(node *ast.Node) *ast.Node { } func isRightSideOfAccessExpression(node *ast.Node) bool { - return node.Parent != nil && (ast.IsPropertyAccessExpression(node.Parent) && node.Parent.Name() == node || - ast.IsElementAccessExpression(node.Parent) && node.Parent.AsElementAccessExpression().ArgumentExpression == node) + return node.Parent() != nil && (ast.IsPropertyAccessExpression(node.Parent()) && node.Parent().Name() == node || + ast.IsElementAccessExpression(node.Parent()) && node.Parent().AsElementAccessExpression().ArgumentExpression() == node) } func isTopLevelInExternalModuleAugmentation(node *ast.Node) bool { - return node != nil && node.Parent != nil && ast.IsModuleBlock(node.Parent) && ast.IsExternalModuleAugmentation(node.Parent.Parent) + return node != nil && node.Parent() != nil && ast.IsModuleBlock(node.Parent()) && ast.IsExternalModuleAugmentation(node.Parent().Parent()) } func isSyntacticDefault(node *ast.Node) bool { @@ -272,13 +272,13 @@ func hasOnlyExpressionInitializer(node *ast.Node) bool { func hasDotDotDotToken(node *ast.Node) bool { switch node.Kind { case ast.KindParameter: - return node.AsParameterDeclaration().DotDotDotToken != nil + return node.AsParameterDeclaration().DotDotDotToken() != nil case ast.KindBindingElement: - return node.AsBindingElement().DotDotDotToken != nil + return node.AsBindingElement().DotDotDotToken() != nil case ast.KindNamedTupleMember: - return node.AsNamedTupleMember().DotDotDotToken != nil + return node.AsNamedTupleMember().DotDotDotToken() != nil case ast.KindJsxExpression: - return node.AsJsxExpression().DotDotDotToken != nil + return node.AsJsxExpression().DotDotDotToken() != nil } return false } @@ -308,19 +308,19 @@ func (c *Checker) isOptionalParameter(node *ast.Node) bool { return false } if node.Initializer() != nil { - signature := c.getSignatureFromDeclaration(node.Parent) - parameterIndex := core.FindIndex(node.Parent.Parameters(), func(p *ast.ParameterDeclarationNode) bool { return p == node }) + signature := c.getSignatureFromDeclaration(node.Parent()) + parameterIndex := core.FindIndex(node.Parent().Parameters(), func(p *ast.ParameterDeclarationNode) bool { return p == node }) debug.Assert(parameterIndex >= 0) // Only consider syntactic or instantiated parameters as optional, not `void` parameters as this function is used // in grammar checks and checking for `void` too early results in parameter types widening too early // and causes some noImplicitAny errors to be lost. return parameterIndex >= c.getMinArgumentCountEx(signature, MinArgumentCountFlagsStrongArityForUntypedJS|MinArgumentCountFlagsVoidIsNonOptional) } - iife := ast.GetImmediatelyInvokedFunctionExpression(node.Parent) + iife := ast.GetImmediatelyInvokedFunctionExpression(node.Parent()) if iife != nil { - parameterIndex := core.FindIndex(node.Parent.Parameters(), func(p *ast.ParameterDeclarationNode) bool { return p == node }) + parameterIndex := core.FindIndex(node.Parent().Parameters(), func(p *ast.ParameterDeclarationNode) bool { return p == node }) return node.Type() == nil && - node.AsParameterDeclaration().DotDotDotToken == nil && + node.AsParameterDeclaration().DotDotDotToken() == nil && parameterIndex >= len(c.getEffectiveCallArguments(iife)) } return false @@ -334,7 +334,7 @@ func declarationBelongsToPrivateAmbientMember(declaration *ast.Node) bool { root := ast.GetRootDeclaration(declaration) memberDeclaration := root if root.Kind == ast.KindParameter { - memberDeclaration = root.Parent + memberDeclaration = root.Parent() } return isPrivateWithinAmbient(memberDeclaration) } @@ -869,7 +869,7 @@ func isObjectLiteralType(t *Type) bool { } func isDeclarationReadonly(declaration *ast.Node) bool { - return ast.GetCombinedModifierFlags(declaration)&ast.ModifierFlagsReadonly != 0 && !ast.IsParameterPropertyDeclaration(declaration, declaration.Parent) + return ast.GetCombinedModifierFlags(declaration)&ast.ModifierFlagsReadonly != 0 && !ast.IsParameterPropertyDeclaration(declaration, declaration.Parent()) } // orderedSetMapThreshold is the size at which an orderedSet materializes its dedup map. @@ -906,7 +906,7 @@ func (s *orderedSet[T]) add(value T) { } func getContainingFunctionOrClassStaticBlock(node *ast.Node) *ast.Node { - return ast.FindAncestor(node.Parent, ast.IsFunctionLikeOrClassStaticBlockDeclaration) + return ast.FindAncestor(node.Parent(), ast.IsFunctionLikeOrClassStaticBlockDeclaration) } func isNodeDescendantOf(node *ast.Node, ancestor *ast.Node) bool { @@ -914,7 +914,7 @@ func isNodeDescendantOf(node *ast.Node, ancestor *ast.Node) bool { if node == ancestor { return true } - node = node.Parent + node = node.Parent() } return false } @@ -1012,7 +1012,7 @@ func isValidESSymbolDeclaration(node *ast.Node) bool { } func isVariableDeclarationInVariableStatement(node *ast.Node) bool { - return ast.IsVariableDeclarationList(node.Parent) && ast.IsVariableStatement(node.Parent.Parent) + return ast.IsVariableDeclarationList(node.Parent()) && ast.IsVariableStatement(node.Parent().Parent()) } func IsKnownSymbol(symbol *ast.Symbol) bool { @@ -1035,7 +1035,7 @@ func isObjectOrArrayLiteralType(t *Type) bool { } func getContainingClassExcludingClassDecorators(node *ast.Node) *ast.ClassLikeDeclaration { - decorator := ast.FindAncestorOrQuit(node.Parent, func(n *ast.Node) ast.FindAncestorResult { + decorator := ast.FindAncestorOrQuit(node.Parent(), func(n *ast.Node) ast.FindAncestorResult { if ast.IsClassLike(n) { return ast.FindAncestorQuit } @@ -1044,8 +1044,8 @@ func getContainingClassExcludingClassDecorators(node *ast.Node) *ast.ClassLikeDe } return ast.FindAncestorFalse }) - if decorator != nil && ast.IsClassLike(decorator.Parent) { - return ast.GetContainingClass(decorator.Parent) + if decorator != nil && ast.IsClassLike(decorator.Parent()) { + return ast.GetContainingClass(decorator.Parent()) } if decorator != nil { return ast.GetContainingClass(decorator) @@ -1059,17 +1059,17 @@ func isThisTypeParameter(t *Type) bool { func isClassInstanceProperty(node *ast.Node) bool { if ast.IsInJSFile(node) && ast.IsExpandoPropertyDeclaration(node) { - left := node.AsBinaryExpression().Left + left := node.AsBinaryExpression().Left() return (!ast.IsBindableStaticAccessExpression(left, false /*excludeThisKeyword*/) || !ast.IsPrototypeAccess(left.Expression())) && !ast.IsBindableStaticNameExpression(left, true /*excludeThisKeyword*/) } - return node.Parent != nil && ast.IsClassLike(node.Parent) && ast.IsPropertyDeclaration(node) && !ast.HasAccessorModifier(node) + return node.Parent() != nil && ast.IsClassLike(node.Parent()) && ast.IsPropertyDeclaration(node) && !ast.HasAccessorModifier(node) } func isThisInitializedObjectBindingExpression(node *ast.Node) bool { - return node != nil && (ast.IsShorthandPropertyAssignment(node) || ast.IsPropertyAssignment(node)) && ast.IsBinaryExpression(node.Parent.Parent) && - node.Parent.Parent.AsBinaryExpression().OperatorToken.Kind == ast.KindEqualsToken && - node.Parent.Parent.AsBinaryExpression().Right.Kind == ast.KindThisKeyword + return node != nil && (ast.IsShorthandPropertyAssignment(node) || ast.IsPropertyAssignment(node)) && ast.IsBinaryExpression(node.Parent().Parent()) && + node.Parent().Parent().AsBinaryExpression().OperatorToken().Kind == ast.KindEqualsToken && + node.Parent().Parent().AsBinaryExpression().Right().Kind == ast.KindThisKeyword } func isThisInitializedDeclaration(node *ast.Node) bool { @@ -1088,14 +1088,14 @@ func (c *Checker) isParameterOrMutableLocalVariable(symbol *ast.Symbol) bool { // Return true if symbol is a parameter, a catch clause variable, or a mutable local variable if symbol.ValueDeclaration != nil { declaration := ast.GetRootDeclaration(symbol.ValueDeclaration) - return declaration != nil && (ast.IsParameterDeclaration(declaration) || ast.IsVariableDeclaration(declaration) && (ast.IsCatchClause(declaration.Parent) || c.isMutableLocalVariableDeclaration(declaration))) + return declaration != nil && (ast.IsParameterDeclaration(declaration) || ast.IsVariableDeclaration(declaration) && (ast.IsCatchClause(declaration.Parent()) || c.isMutableLocalVariableDeclaration(declaration))) } return false } func (c *Checker) isMutableLocalVariableDeclaration(declaration *ast.Node) bool { // Return true if symbol is a non-exported and non-global `let` variable - return declaration.Parent.Flags&ast.NodeFlagsLet != 0 && !(ast.GetCombinedModifierFlags(declaration)&ast.ModifierFlagsExport != 0 || declaration.Parent.Parent.Kind == ast.KindVariableStatement && ast.IsGlobalSourceFile(declaration.Parent.Parent.Parent)) + return declaration.Parent().Flags&ast.NodeFlagsLet != 0 && !(ast.GetCombinedModifierFlags(declaration)&ast.ModifierFlagsExport != 0 || declaration.Parent().Parent().Kind == ast.KindVariableStatement && ast.IsGlobalSourceFile(declaration.Parent().Parent().Parent())) } func isInAmbientOrTypeNode(node *ast.Node) bool { @@ -1148,12 +1148,12 @@ func getMembersOfDeclaration(node *ast.Node) []*ast.Node { } func isInRightSideOfImportOrExportAssignment(node *ast.EntityName) bool { - for node.Parent.Kind == ast.KindQualifiedName { - node = node.Parent + for node.Parent().Kind == ast.KindQualifiedName { + node = node.Parent() } - return node.Parent.Kind == ast.KindImportEqualsDeclaration && node.Parent.AsImportEqualsDeclaration().ModuleReference == node || - node.Parent.Kind == ast.KindExportAssignment && node.Parent.Expression() == node + return node.Parent().Kind == ast.KindImportEqualsDeclaration && node.Parent().AsImportEqualsDeclaration().ModuleReference() == node || + node.Parent().Kind == ast.KindExportAssignment && node.Parent().Expression() == node } func isJsxIntrinsicTagName(tagName *ast.Node) bool { @@ -1163,22 +1163,22 @@ func isJsxIntrinsicTagName(tagName *ast.Node) bool { func getContainingObjectLiteral(f *ast.SignatureDeclaration) *ast.Node { if (f.Kind == ast.KindMethodDeclaration || f.Kind == ast.KindGetAccessor || - f.Kind == ast.KindSetAccessor) && f.Parent.Kind == ast.KindObjectLiteralExpression { - return f.Parent - } else if f.Kind == ast.KindFunctionExpression && f.Parent.Kind == ast.KindPropertyAssignment { - return f.Parent.Parent + f.Kind == ast.KindSetAccessor) && f.Parent().Kind == ast.KindObjectLiteralExpression { + return f.Parent() + } else if f.Kind == ast.KindFunctionExpression && f.Parent().Kind == ast.KindPropertyAssignment { + return f.Parent().Parent() } return nil } func isImportTypeQualifierPart(node *ast.Node) *ast.Node { - parent := node.Parent + parent := node.Parent() for ast.IsQualifiedName(parent) { node = parent - parent = parent.Parent + parent = parent.Parent() } - if parent != nil && parent.Kind == ast.KindImportType && parent.AsImportTypeNode().Qualifier == node { + if parent != nil && parent.Kind == ast.KindImportType && parent.AsImportTypeNode().Qualifier() == node { return parent } @@ -1186,11 +1186,11 @@ func isImportTypeQualifierPart(node *ast.Node) *ast.Node { } func isInNameOfExpressionWithTypeArgumentsOrHeritageTypeReference(node *ast.Node) bool { - for node.Parent.Kind == ast.KindPropertyAccessExpression || node.Parent.Kind == ast.KindQualifiedName { - node = node.Parent + for node.Parent().Kind == ast.KindPropertyAccessExpression || node.Parent().Kind == ast.KindQualifiedName { + node = node.Parent() } - return node.Parent.Kind == ast.KindExpressionWithTypeArguments || + return node.Parent().Kind == ast.KindExpressionWithTypeArguments || ast.IsNameOfHeritageClauseTypeReference(node) } @@ -1202,19 +1202,19 @@ func getIndexSymbolFromSymbolTable(symbolTable ast.SymbolTable) *ast.Symbol { // NOTE: This requires a node with a valid `parent` pointer. func expressionResultIsUnused(node *ast.Node) bool { for { - parent := node.Parent + parent := node.Parent() // walk up parenthesized expressions, but keep a pointer to the top-most parenthesized expression if ast.IsParenthesizedExpression(parent) { node = parent continue } // result is unused in an expression statement, `void` expression, or the initializer or incrementer of a `for` loop - if ast.IsExpressionStatement(parent) || ast.IsVoidExpression(parent) || ast.IsForStatement(parent) && (parent.Initializer() == node || parent.AsForStatement().Incrementor == node) { + if ast.IsExpressionStatement(parent) || ast.IsVoidExpression(parent) || ast.IsForStatement(parent) && (parent.Initializer() == node || parent.AsForStatement().Incrementor() == node) { return true } - if ast.IsBinaryExpression(parent) && parent.AsBinaryExpression().OperatorToken.Kind == ast.KindCommaToken { + if ast.IsBinaryExpression(parent) && parent.AsBinaryExpression().OperatorToken().Kind == ast.KindCommaToken { // left side of comma is always unused - if node == parent.AsBinaryExpression().Left { + if node == parent.AsBinaryExpression().Left() { return true } // right side of comma is unused if parent is unused @@ -1231,13 +1231,13 @@ func pseudoBigIntToString(value jsnum.PseudoBigInt) string { func getSuperContainer(node *ast.Node, stopOnFunctions bool) *ast.Node { for { - node = node.Parent + node = node.Parent() if node == nil { return nil } switch node.Kind { case ast.KindComputedPropertyName: - node = node.Parent + node = node.Parent() case ast.KindFunctionDeclaration, ast.KindFunctionExpression, ast.KindArrowFunction: if !stopOnFunctions { continue @@ -1248,14 +1248,14 @@ func getSuperContainer(node *ast.Node, stopOnFunctions bool) *ast.Node { return node case ast.KindDecorator: // Decorators are always applied outside of the body of a class or method. - if ast.IsParameterDeclaration(node.Parent) && ast.IsClassElement(node.Parent.Parent) { + if ast.IsParameterDeclaration(node.Parent()) && ast.IsClassElement(node.Parent().Parent()) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. - node = node.Parent.Parent - } else if ast.IsClassElement(node.Parent) { + node = node.Parent().Parent() + } else if ast.IsClassElement(node.Parent()) { // If the decorator's parent is a class element, we resolve the 'this' container // from the parent class declaration. - node = node.Parent + node = node.Parent() } } } @@ -1296,7 +1296,7 @@ func forEachYieldExpression(body *ast.Node, visitor func(expr *ast.Node) bool) b } func getEnclosingContainer(node *ast.Node) *ast.Node { - return ast.FindAncestor(node.Parent, func(n *ast.Node) bool { + return ast.FindAncestor(node.Parent(), func(n *ast.Node) bool { return binder.GetContainerFlags(n)&binder.ContainerFlagsIsContainer != 0 }) } @@ -1619,8 +1619,8 @@ func tryGetPropertyAccessOrIdentifierToString(expr *ast.Node) string { } case ast.IsElementAccessExpression(expr): baseStr := tryGetPropertyAccessOrIdentifierToString(expr.Expression()) - if baseStr != "" && ast.IsPropertyName(expr.AsElementAccessExpression().ArgumentExpression) { - return baseStr + "." + ast.GetPropertyNameForPropertyNameNode(expr.AsElementAccessExpression().ArgumentExpression) + if baseStr != "" && ast.IsPropertyName(expr.AsElementAccessExpression().ArgumentExpression()) { + return baseStr + "." + ast.GetPropertyNameForPropertyNameNode(expr.AsElementAccessExpression().ArgumentExpression()) } case ast.IsIdentifier(expr): return expr.Text() @@ -1660,11 +1660,11 @@ func getAnyImportSyntax(node *ast.Node) *ast.Node { case ast.KindImportEqualsDeclaration: importNode = node case ast.KindImportClause: - importNode = node.Parent + importNode = node.Parent() case ast.KindNamespaceImport: - importNode = node.Parent.Parent + importNode = node.Parent().Parent() case ast.KindImportSpecifier: - importNode = node.Parent.Parent.Parent + importNode = node.Parent().Parent().Parent() default: return nil } @@ -1904,9 +1904,9 @@ func CreateModeMismatchDetails(program Program, file *ast.SourceFile) Diagnostic } func walkUpOuterExpressions(node *ast.Node) *ast.Node { - parent := node.Parent + parent := node.Parent() for parent != nil && ast.IsOuterExpression(parent, ast.OEKAll) { - parent = parent.Parent + parent = parent.Parent() } return parent } diff --git a/tsc/internal/compiler/fileloader.go b/tsc/internal/compiler/fileloader.go index d4e159246c6ca..07f4dc7a93d36 100644 --- a/tsc/internal/compiler/fileloader.go +++ b/tsc/internal/compiler/fileloader.go @@ -872,7 +872,7 @@ func (p *fileLoader) resolveImportsAndModuleAugmentations(t *parseTask) { for index, entry := range moduleNames { moduleName := entry.Text() - if moduleName == "" || ast.IsSourcePhaseImport(entry.Parent) { + if moduleName == "" || ast.IsSourcePhaseImport(entry.Parent()) { continue } @@ -945,8 +945,8 @@ func (p *fileLoader) createSyntheticImport(text string, file *ast.SourceFile) *a defer p.factoryMu.Unlock() externalHelpersModuleReference := p.factory.NewStringLiteral(text, ast.TokenFlagsNone) importDecl := p.factory.NewImportDeclaration(nil, nil, externalHelpersModuleReference, nil) - externalHelpersModuleReference.Parent = importDecl - importDecl.Parent = file.AsNode() + externalHelpersModuleReference.SetParent(importDecl) + importDecl.SetParent(file.AsNode()) return externalHelpersModuleReference } @@ -1035,26 +1035,26 @@ func getDefaultResolutionModeForFile(fileName tspath.RootedFilePath, meta ast.So } func getModeForUsageLocation(fileName tspath.RootedFilePath, meta ast.SourceFileMetaData, usage *ast.StringLiteralLike, options *core.CompilerOptions) core.ResolutionMode { - if ast.IsImportDeclaration(usage.Parent) || usage.Parent.Kind == ast.KindJSImportDeclaration || ast.IsExportDeclaration(usage.Parent) || ast.IsJSDocImportTag(usage.Parent) { - isTypeOnly := ast.IsExclusivelyTypeOnlyImportOrExport(usage.Parent) + if ast.IsImportDeclaration(usage.Parent()) || usage.Parent().Kind == ast.KindJSImportDeclaration || ast.IsExportDeclaration(usage.Parent()) || ast.IsJSDocImportTag(usage.Parent()) { + isTypeOnly := ast.IsExclusivelyTypeOnlyImportOrExport(usage.Parent()) if isTypeOnly { var override core.ResolutionMode var ok bool - switch usage.Parent.Kind { + switch usage.Parent().Kind { case ast.KindImportDeclaration, ast.KindJSImportDeclaration: - override, ok = usage.Parent.AsImportDeclaration().Attributes.GetResolutionModeOverride(nil) + override, ok = usage.Parent().AsImportDeclaration().Attributes().GetResolutionModeOverride(nil) case ast.KindExportDeclaration: - override, ok = usage.Parent.AsExportDeclaration().Attributes.GetResolutionModeOverride(nil) + override, ok = usage.Parent().AsExportDeclaration().Attributes().GetResolutionModeOverride(nil) case ast.KindJSDocImportTag: - override, ok = usage.Parent.AsJSDocImportTag().Attributes.GetResolutionModeOverride(nil) + override, ok = usage.Parent().AsJSDocImportTag().Attributes().GetResolutionModeOverride(nil) } if ok { return override } } } - if ast.IsLiteralTypeNode(usage.Parent) && ast.IsImportTypeNode(usage.Parent.Parent) { - if override, ok := usage.Parent.Parent.AsImportTypeNode().Attributes.GetResolutionModeOverride(nil); ok { + if ast.IsLiteralTypeNode(usage.Parent()) && ast.IsImportTypeNode(usage.Parent().Parent()) { + if override, ok := usage.Parent().Parent().AsImportTypeNode().Attributes().GetResolutionModeOverride(nil); ok { return override } } @@ -1073,11 +1073,11 @@ func importSyntaxAffectsModuleResolution(options *core.CompilerOptions) bool { } func getEmitSyntaxForUsageLocationWorker(fileName tspath.RootedFilePath, meta ast.SourceFileMetaData, usage *ast.Node, options *core.CompilerOptions) core.ResolutionMode { - if ast.IsRequireCall(usage.Parent, false /*requireStringLiteralLikeArgument*/) || ast.IsExternalModuleReference(usage.Parent) && ast.IsImportEqualsDeclaration(usage.Parent.Parent) { + if ast.IsRequireCall(usage.Parent(), false /*requireStringLiteralLikeArgument*/) || ast.IsExternalModuleReference(usage.Parent()) && ast.IsImportEqualsDeclaration(usage.Parent().Parent()) { return core.ModuleKindCommonJS } fileEmitMode := ast.GetEmitModuleFormatOfFileWorker(fileName, options, meta) - if call := ast.WalkUpParenthesizedExpressions(usage.Parent); ast.IsImportCall(call) { + if call := ast.WalkUpParenthesizedExpressions(usage.Parent()); ast.IsImportCall(call) { if ast.IsSourcePhaseImportCall(call) { return core.ModuleKindESNext } diff --git a/tsc/internal/compiler/includeprocessor.go b/tsc/internal/compiler/includeprocessor.go index b2fd0ab365e68..05eba182d78ae 100644 --- a/tsc/internal/compiler/includeprocessor.go +++ b/tsc/internal/compiler/includeprocessor.go @@ -102,9 +102,9 @@ func (i *includeProcessor) getCompilerOptionsObjectLiteralSyntax(program *Progra configFile := program.opts.Config.ConfigFile if configFile != nil { if compilerOptionsProperty := tsoptions.ForEachTsConfigPropArray(configFile.SourceFile, "compilerOptions", core.Identity); compilerOptionsProperty != nil && - compilerOptionsProperty.Initializer != nil && - ast.IsObjectLiteralExpression(compilerOptionsProperty.Initializer) { - i.compilerOptionsSyntax = compilerOptionsProperty.Initializer.AsObjectLiteralExpression() + compilerOptionsProperty.Initializer() != nil && + ast.IsObjectLiteralExpression(compilerOptionsProperty.Initializer()) { + i.compilerOptionsSyntax = compilerOptionsProperty.Initializer().AsObjectLiteralExpression() } } else { i.compilerOptionsSyntax = nil diff --git a/tsc/internal/compiler/program.go b/tsc/internal/compiler/program.go index 31363f95afc88..5771c420bd8f7 100644 --- a/tsc/internal/compiler/program.go +++ b/tsc/internal/compiler/program.go @@ -480,7 +480,7 @@ func (p *Program) canReplaceFileInProgram(file1 *ast.SourceFile, file2 *ast.Sour slices.EqualFunc(file1.Imports(), file2.Imports(), func(n1 *ast.Node, n2 *ast.Node) bool { return equalModuleSpecifiers(n1, n2) && p.GetModeForUsageLocation(file1, n1) == p.GetModeForUsageLocation(file2, n2) && - ast.IsSourcePhaseImport(n1.Parent) == ast.IsSourcePhaseImport(n2.Parent) + ast.IsSourcePhaseImport(n1.Parent()) == ast.IsSourcePhaseImport(n2.Parent()) }) && slices.EqualFunc(file1.ModuleAugmentations, file2.ModuleAugmentations, equalModuleAugmentationNames) && slices.Equal(file1.AmbientModuleNames, file2.AmbientModuleNames) && @@ -654,7 +654,7 @@ func (p *Program) GetResolvedModuleFromModuleSpecifier(file ast.HasFileName, mod if !ast.IsStringLiteralLike(moduleSpecifier) { panic("moduleSpecifier must be a StringLiteralLike") } - if ast.IsSourcePhaseImport(moduleSpecifier.Parent) { + if ast.IsSourcePhaseImport(moduleSpecifier.Parent()) { return nil } mode := p.GetModeForUsageLocation(file, moduleSpecifier) @@ -932,16 +932,16 @@ func (p *Program) verifyCompilerOptions() { getCompilerOptionsObjectLiteralSyntax := core.Memoize(func() *ast.ObjectLiteralExpression { compilerOptionsProperty := getCompilerOptionsPropertySyntax() if compilerOptionsProperty != nil && - compilerOptionsProperty.Initializer != nil && - ast.IsObjectLiteralExpression(compilerOptionsProperty.Initializer) { - return compilerOptionsProperty.Initializer.AsObjectLiteralExpression() + compilerOptionsProperty.Initializer() != nil && + ast.IsObjectLiteralExpression(compilerOptionsProperty.Initializer()) { + return compilerOptionsProperty.Initializer().AsObjectLiteralExpression() } return nil }) createOptionDiagnosticInObjectLiteralSyntax := func(objectLiteral *ast.ObjectLiteralExpression, onKey bool, key1 string, key2 string, message *diagnostics.Message, args ...any) *ast.Diagnostic { diag := tsoptions.ForEachPropertyAssignment(objectLiteral, key1, func(property *ast.PropertyAssignment) *ast.Diagnostic { - return tsoptions.CreateDiagnosticForNodeInSourceFile(sourceFile(), core.IfElse(onKey, property.Name(), property.Initializer), message, args...) + return tsoptions.CreateDiagnosticForNodeInSourceFile(sourceFile(), core.IfElse(onKey, property.Name(), property.Initializer()), message, args...) }, key2) if diag != nil { p.programDiagnostics = append(p.programDiagnostics, diag) @@ -1125,8 +1125,8 @@ func (p *Program) verifyCompilerOptions() { createDiagnosticForOptionPaths := func(onKey bool, key string, message *diagnostics.Message, args ...any) *ast.Diagnostic { diag := forEachOptionPathsSyntax(func(pathProp *ast.PropertyAssignment) *ast.Diagnostic { - if ast.IsObjectLiteralExpression(pathProp.Initializer) { - return createOptionDiagnosticInObjectLiteralSyntax(pathProp.Initializer.AsObjectLiteralExpression(), onKey, key, "", message, args...) + if ast.IsObjectLiteralExpression(pathProp.Initializer()) { + return createOptionDiagnosticInObjectLiteralSyntax(pathProp.Initializer().AsObjectLiteralExpression(), onKey, key, "", message, args...) } return nil }) @@ -1138,9 +1138,9 @@ func (p *Program) verifyCompilerOptions() { createDiagnosticForOptionPathKeyValue := func(key string, valueIndex int, message *diagnostics.Message, args ...any) *ast.Diagnostic { diag := forEachOptionPathsSyntax(func(pathProp *ast.PropertyAssignment) *ast.Diagnostic { - if ast.IsObjectLiteralExpression(pathProp.Initializer) { - return tsoptions.ForEachPropertyAssignment(pathProp.Initializer.AsObjectLiteralExpression(), key, func(keyProps *ast.PropertyAssignment) *ast.Diagnostic { - initializer := keyProps.Initializer + if ast.IsObjectLiteralExpression(pathProp.Initializer()) { + return tsoptions.ForEachPropertyAssignment(pathProp.Initializer().AsObjectLiteralExpression(), key, func(keyProps *ast.PropertyAssignment) *ast.Diagnostic { + initializer := keyProps.Initializer() if ast.IsArrayLiteralExpression(initializer) { elements := initializer.ElementList() if elements != nil && len(elements.Nodes) > valueIndex { @@ -2263,7 +2263,7 @@ func (p *Program) collectPackageNames() *packageNamesInfo { continue } for _, imp := range file.Imports() { - if ast.IsSourcePhaseImport(imp.Parent) || tspath.IsExternalModuleNameRelative(imp.Text()) { + if ast.IsSourcePhaseImport(imp.Parent()) || tspath.IsExternalModuleNameRelative(imp.Text()) { continue } if resolvedModules, ok := p.resolvedModules[file.PathKey()]; ok { diff --git a/tsc/internal/compiler/program_test.go b/tsc/internal/compiler/program_test.go index 0139968b1591b..9c1de628ac0dd 100644 --- a/tsc/internal/compiler/program_test.go +++ b/tsc/internal/compiler/program_test.go @@ -515,7 +515,7 @@ func TestImportSourceProgram(t *testing.T) { assert.Assert(t, program.GetSourceFile("/src/a.ts") != nil) for _, specifier := range file.Imports() { resolved := program.GetResolvedModuleFromModuleSpecifier(file, specifier) - assert.Equal(t, resolved.IsResolved(), !ast.IsSourcePhaseImport(specifier.Parent)) + assert.Equal(t, resolved.IsResolved(), !ast.IsSourcePhaseImport(specifier.Parent())) } files["/src/index.ts"] = content @@ -530,7 +530,7 @@ func TestImportSourceProgram(t *testing.T) { file = program.GetSourceFile("/src/index.ts") for _, specifier := range file.Imports() { resolved := program.GetResolvedModuleFromModuleSpecifier(file, specifier) - assert.Equal(t, resolved.IsResolved(), !ast.IsSourcePhaseImport(specifier.Parent)) + assert.Equal(t, resolved.IsResolved(), !ast.IsSourcePhaseImport(specifier.Parent())) } }) } diff --git a/tsc/internal/core/arena.go b/tsc/internal/core/arena.go index 87e231f70c781..66f2bcf216b7f 100644 --- a/tsc/internal/core/arena.go +++ b/tsc/internal/core/arena.go @@ -6,6 +6,10 @@ import "slices" type Arena[T any] struct { data []T + // OnGrow, when set, is called with every block of memory the arena allocates. An owner + // whose pointers into the arena are invisible to the garbage collector uses it to keep + // the blocks alive. + OnGrow func(block []T) } // Allocate a single element in the arena and return a pointer to the element. If the arena is at capacity, @@ -15,6 +19,9 @@ func (a *Arena[T]) New() *T { nextSize := nextArenaSize(len(a.data)) // Use the same trick as slices.Concat; Grow rounds up to the next size class. a.data = slices.Grow[[]T](nil, nextSize) + if a.OnGrow != nil { + a.OnGrow(a.data[:cap(a.data)]) + } } index := len(a.data) a.data = a.data[:index+1] @@ -32,10 +39,17 @@ func (a *Arena[T]) NewSlice(size int) []T { if len(a.data)+size > cap(a.data) { nextSize := nextArenaSize(len(a.data)) if size > nextSize { - return make([]T, size) + slice := make([]T, size) + if a.OnGrow != nil { + a.OnGrow(slice) + } + return slice } // Use the same trick as slices.Concat; Grow rounds up to the next size class. a.data = slices.Grow[[]T](nil, nextSize) + if a.OnGrow != nil { + a.OnGrow(a.data[:cap(a.data)]) + } } newLen := len(a.data) + size slice := a.data[len(a.data):newLen:newLen] diff --git a/tsc/internal/evaluator/evaluator.go b/tsc/internal/evaluator/evaluator.go index 136918a9ef4b7..c542ed7f726f9 100644 --- a/tsc/internal/evaluator/evaluator.go +++ b/tsc/internal/evaluator/evaluator.go @@ -42,7 +42,7 @@ func NewEvaluator(evaluateEntity Evaluator, outerExpressionsToSkip ast.OuterExpr expr = ast.SkipOuterExpressions(expr, outerExpressionsToSkip|ast.OEKParentheses) switch expr.Kind { case ast.KindPrefixUnaryExpression: - result := evaluate(expr.AsPrefixUnaryExpression().Operand, location) + result := evaluate(expr.AsPrefixUnaryExpression().Operand(), location) resolvedOtherFiles = result.ResolvedOtherFiles hasExternalReferences = result.HasExternalReferences if value, ok := result.Value.(jsnum.Number); ok { @@ -56,10 +56,10 @@ func NewEvaluator(evaluateEntity Evaluator, outerExpressionsToSkip ast.OuterExpr } } case ast.KindBinaryExpression: - left := evaluate(expr.AsBinaryExpression().Left, location) - right := evaluate(expr.AsBinaryExpression().Right, location) - operator := expr.AsBinaryExpression().OperatorToken.Kind - isSyntacticallyString = (left.IsSyntacticallyString || right.IsSyntacticallyString) && expr.AsBinaryExpression().OperatorToken.Kind == ast.KindPlusToken + left := evaluate(expr.AsBinaryExpression().Left(), location) + right := evaluate(expr.AsBinaryExpression().Right(), location) + operator := expr.AsBinaryExpression().OperatorToken().Kind + isSyntacticallyString = (left.IsSyntacticallyString || right.IsSyntacticallyString) && expr.AsBinaryExpression().OperatorToken().Kind == ast.KindPlusToken resolvedOtherFiles = left.ResolvedOtherFiles || right.ResolvedOtherFiles hasExternalReferences = left.HasExternalReferences || right.HasExternalReferences leftNum, leftIsNum := left.Value.(jsnum.Number) @@ -123,16 +123,16 @@ func NewEvaluator(evaluateEntity Evaluator, outerExpressionsToSkip ast.OuterExpr func evaluateTemplateExpression(expr *ast.Node, location *ast.Node, evaluate Evaluator) Result { var sb strings.Builder - sb.WriteString(expr.AsTemplateExpression().Head.Text()) + sb.WriteString(expr.AsTemplateExpression().Head().Text()) resolvedOtherFiles := false hasExternalReferences := false - for _, span := range expr.AsTemplateExpression().TemplateSpans.Nodes { + for _, span := range expr.AsTemplateExpression().TemplateSpans().Nodes { spanResult := evaluate(span.Expression(), location) if spanResult.Value == nil { return Result{nil, true /*isSyntacticallyString*/, false, false} } sb.WriteString(AnyToString(spanResult.Value)) - sb.WriteString(span.AsTemplateSpan().Literal.Text()) + sb.WriteString(span.AsTemplateSpan().Literal().Text()) resolvedOtherFiles = resolvedOtherFiles || spanResult.ResolvedOtherFiles hasExternalReferences = hasExternalReferences || spanResult.HasExternalReferences } diff --git a/tsc/internal/execute/incremental/programtosnapshot.go b/tsc/internal/execute/incremental/programtosnapshot.go index 3470c2dc41082..0f4fb5ccbe094 100644 --- a/tsc/internal/execute/incremental/programtosnapshot.go +++ b/tsc/internal/execute/incremental/programtosnapshot.go @@ -237,7 +237,7 @@ func fileAffectsGlobalScope(file *ast.SourceFile) bool { // if file contains anything that augments to global scope we need to build them as if // they are global files as well as module if core.Some(file.ModuleAugmentations, func(augmentation *ast.ModuleName) bool { - return ast.IsGlobalScopeAugmentation(augmentation.Parent) + return ast.IsGlobalScopeAugmentation(augmentation.Parent()) }) { return true } diff --git a/tsc/internal/format/api.go b/tsc/internal/format/api.go index bcb42bf18e886..40fb4f6f6ea3a 100644 --- a/tsc/internal/format/api.go +++ b/tsc/internal/format/api.go @@ -121,7 +121,7 @@ func FormatOnOpeningCurly(ctx context.Context, sourceFile *ast.SourceFile, posit if openingCurly == nil { return nil } - curlyBraceRange := openingCurly.Parent + curlyBraceRange := openingCurly.Parent() outermostNode := findOutermostNodeWithinListLevel(curlyBraceRange) /** * We limit the span to end at the opening curly to handle the case where diff --git a/tsc/internal/format/indent.go b/tsc/internal/format/indent.go index f440423b64397..e479895c883be 100644 --- a/tsc/internal/format/indent.go +++ b/tsc/internal/format/indent.go @@ -77,12 +77,12 @@ func GetIndentation(position int, sourceFile *ast.SourceFile, options lsutil.For // y: undefined, // } // ``` - isObjectLiteral := currentToken.Kind == ast.KindOpenBraceToken && currentToken.Parent != nil && currentToken.Parent.Kind == ast.KindObjectLiteralExpression + isObjectLiteral := currentToken.Kind == ast.KindOpenBraceToken && currentToken.Parent() != nil && currentToken.Parent().Kind == ast.KindObjectLiteralExpression if options.IndentStyle == lsutil.IndentStyleBlock || isObjectLiteral { return getBlockIndent(sourceFile, position, options) } - if precedingToken.Kind == ast.KindCommaToken && precedingToken.Parent != nil && precedingToken.Parent.Kind != ast.KindBinaryExpression { + if precedingToken.Kind == ast.KindCommaToken && precedingToken.Parent() != nil && precedingToken.Parent().Kind != ast.KindBinaryExpression { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it actualIndentation := getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options) if actualIndentation != -1 { @@ -90,10 +90,10 @@ func GetIndentation(position int, sourceFile *ast.SourceFile, options lsutil.For } } - containerList := getListByPosition(position, precedingToken.Parent, sourceFile) + containerList := getListByPosition(position, precedingToken.Parent(), sourceFile) // use list position if the preceding token is before any list items if containerList != nil && !precedingToken.Loc.ContainedBy(containerList.Loc) { - useTheSameBaseIndentation := currentToken.Parent != nil && (currentToken.Parent.Kind == ast.KindFunctionExpression || currentToken.Parent.Kind == ast.KindArrowFunction) + useTheSameBaseIndentation := currentToken.Parent() != nil && (currentToken.Parent().Kind == ast.KindFunctionExpression || currentToken.Parent().Kind == ast.KindArrowFunction) indentSize := 0 if !useTheSameBaseIndentation { indentSize = options.IndentSize @@ -149,7 +149,7 @@ func getRangeOfEnclosingComment( tokenAtPosition := astnav.GetTokenAtPosition(sourceFile, position) jsdoc := ast.FindAncestor(tokenAtPosition, (*ast.Node).IsJSDoc) if jsdoc != nil { - tokenAtPosition = jsdoc.Parent + tokenAtPosition = jsdoc.Parent() } tokenStart := astnav.GetStartOfNode(tokenAtPosition, sourceFile, false /*includeJSDoc*/) if tokenStart <= position && position < tokenAtPosition.End() { @@ -192,7 +192,7 @@ func getBlockIndent(sourceFile *ast.SourceFile, position int, options lsutil.For func getActualIndentationForListItemBeforeComma(commaToken *ast.Node, sourceFile *ast.SourceFile, options lsutil.FormatCodeSettings) int { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it - if commaToken.Parent == nil { + if commaToken.Parent() == nil { return -1 } containingList := GetContainingList(commaToken, sourceFile) @@ -270,7 +270,7 @@ func getSmartIndent(sourceFile *ast.SourceFile, position int, precedingToken *as } previous = current - current = current.Parent + current = current.Parent() } // no parent was found - return the base indentation of the SourceFile return options.BaseIndentSize @@ -286,7 +286,7 @@ func getIndentationForNodeWorker( isNextChild bool, options lsutil.FormatCodeSettings, ) int { - parent := current.Parent + parent := current.Parent() // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if // * parent and child nodes start on the same line, or @@ -359,7 +359,7 @@ func getIndentationForNodeWorker( useTrueStart := isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, current, currentStartLine, sourceFile) current = parent - parent = current.Parent + parent = current.Parent() if useTrueStart { currentStartLine, currentStartCharacter = scanner.GetECMALineAndByteOffsetOfPosition(sourceFile, scanner.GetTokenPosOfNode(current, sourceFile, false)) @@ -398,7 +398,7 @@ func isArgumentAndStartLineOverlapsExpressionBeingCalled(parent *ast.Node, child } func getActualIndentationForListItem(node *ast.Node, sourceFile *ast.SourceFile, options lsutil.FormatCodeSettings, listIndentsChild bool) int { - if node.Parent != nil && node.Parent.Kind == ast.KindVariableDeclarationList { + if node.Parent() != nil && node.Parent().Kind == ast.KindVariableDeclarationList { // VariableDeclarationList has no wrapping tokens return -1 } @@ -498,7 +498,7 @@ func findFirstNonWhitespaceCharacterAndColumn(startPos int, endPos int, sourceFi } func childStartsOnTheSameLineWithElseInIfStatement(parent *ast.Node, child *ast.Node, childStartLine int, sourceFile *ast.SourceFile) bool { - if parent.Kind == ast.KindIfStatement && parent.AsIfStatement().ElseStatement == child { + if parent.Kind == ast.KindIfStatement && parent.AsIfStatement().ElseStatement() == child { elseKeyword := astnav.FindPrecedingToken(sourceFile, child.Pos()) debug.Assert(elseKeyword != nil) elseKeywordStartLine := getStartLineForNode(elseKeyword, sourceFile) @@ -516,10 +516,10 @@ func getStartLineForNode(n *ast.Node, sourceFile *ast.SourceFile) int { } func GetContainingList(node *ast.Node, sourceFile *ast.SourceFile) *ast.NodeList { - if node.Parent == nil { + if node.Parent() == nil { return nil } - return getListByRange(scanner.GetTokenPosOfNode(node, sourceFile, false), node.End(), node.Parent, sourceFile) + return getListByRange(scanner.GetTokenPosOfNode(node, sourceFile, false), node.End(), node.Parent(), sourceFile) } func getListByPosition(pos int, node *ast.Node, sourceFile *ast.SourceFile) *ast.NodeList { @@ -569,7 +569,7 @@ 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) + return getList(node.AsVariableDeclarationList().Declarations(), r, node, sourceFile) case ast.KindObjectBindingPattern, ast.KindArrayBindingPattern, ast.KindNamedImports, ast.KindNamedExports: return getList(node.ElementList(), r, node, sourceFile) } @@ -730,7 +730,7 @@ func NodeWillIndentChild(settings lsutil.FormatCodeSettings, parent *ast.Node, c case ast.KindExportDeclaration: return childKind != ast.KindNamedExports case ast.KindImportDeclaration: - return childKind != ast.KindImportClause || (child.AsImportClause().NamedBindings != nil && child.AsImportClause().NamedBindings.Kind != ast.KindNamedImports) + return childKind != ast.KindImportClause || (child.AsImportClause().NamedBindings() != nil && child.AsImportClause().NamedBindings().Kind != ast.KindNamedImports) case ast.KindJsxElement: return childKind != ast.KindJsxClosingElement case ast.KindJsxFragment: @@ -777,9 +777,9 @@ func NodeWillIndentChild(settings lsutil.FormatCodeSettings, parent *ast.Node, c // we check for the whenTrue branch beginning on the line that the condition ends, and the whenFalse // branch beginning on the line that the whenTrue branch ends. func childIsUnindentedBranchOfConditionalExpression(parent *ast.Node, child *ast.Node, childStartLine int, sourceFile *ast.SourceFile) bool { - if parent.Kind == ast.KindConditionalExpression && (child == parent.AsConditionalExpression().WhenTrue || child == parent.AsConditionalExpression().WhenFalse) { - conditionEndLine := scanner.GetECMALineOfPosition(sourceFile, parent.AsConditionalExpression().Condition.End()) - if child == parent.AsConditionalExpression().WhenTrue { + if parent.Kind == ast.KindConditionalExpression && (child == parent.AsConditionalExpression().WhenTrue() || child == parent.AsConditionalExpression().WhenFalse()) { + conditionEndLine := scanner.GetECMALineOfPosition(sourceFile, parent.AsConditionalExpression().Condition().End()) + if child == parent.AsConditionalExpression().WhenTrue() { return childStartLine == conditionEndLine } else { // On the whenFalse side, we have to look at the whenTrue side, because if that one was @@ -789,8 +789,8 @@ func childIsUnindentedBranchOfConditionalExpression(parent *ast.Node, child *ast // ? 1 : ( L1: whenTrue indented because it's on a new line // 0 L2: indented two stops, one because whenTrue was indented // ); and one because of the parentheses spanning multiple lines - trueStartLine := getStartLineForNode(parent.AsConditionalExpression().WhenTrue, sourceFile) - trueEndLine := scanner.GetECMALineOfPosition(sourceFile, parent.AsConditionalExpression().WhenTrue.End()) + trueStartLine := getStartLineForNode(parent.AsConditionalExpression().WhenTrue(), sourceFile) + trueEndLine := scanner.GetECMALineOfPosition(sourceFile, parent.AsConditionalExpression().WhenTrue().End()) return conditionEndLine == trueStartLine && trueEndLine == childStartLine } } diff --git a/tsc/internal/format/rulecontext.go b/tsc/internal/format/rulecontext.go index 175f43752f396..a6674e6fdce67 100644 --- a/tsc/internal/format/rulecontext.go +++ b/tsc/internal/format/rulecontext.go @@ -146,7 +146,7 @@ func isNotForContext(context *FormattingContext) bool { func isBinaryOpContext(context *FormattingContext) bool { switch context.contextNode.Kind { case ast.KindBinaryExpression: - return context.contextNode.AsBinaryExpression().OperatorToken.Kind != ast.KindCommaToken + return context.contextNode.AsBinaryExpression().OperatorToken().Kind != ast.KindCommaToken case ast.KindConditionalExpression, ast.KindConditionalType, ast.KindAsExpression, @@ -337,7 +337,7 @@ func isAfterCodeBlockContext(context *FormattingContext) bool { ast.KindSwitchStatement: return true case ast.KindBlock: - blockParent := context.currentTokenParent.Parent + blockParent := context.currentTokenParent.Parent() // In a codefix scenario, we can't rely on parents being set. So just always return true. if blockParent == nil || blockParent.Kind != ast.KindArrowFunction && blockParent.Kind != ast.KindFunctionExpression { return true @@ -421,7 +421,7 @@ func isJsxExpressionContext(context *FormattingContext) bool { } func isNextTokenParentJsxAttribute(context *FormattingContext) bool { - return context.nextTokenParent.Kind == ast.KindJsxAttribute || (context.nextTokenParent.Kind == ast.KindJsxNamespacedName && context.nextTokenParent.Parent.Kind == ast.KindJsxAttribute) + return context.nextTokenParent.Kind == ast.KindJsxAttribute || (context.nextTokenParent.Kind == ast.KindJsxNamespacedName && context.nextTokenParent.Parent().Kind == ast.KindJsxAttribute) } func isJsxAttributeContext(context *FormattingContext) bool { @@ -453,7 +453,7 @@ func isEndOfDecoratorContextOnSameLine(context *FormattingContext) bool { func nodeIsInDecoratorContext(node *ast.Node) bool { for node != nil && ast.IsExpression(node) { - node = node.Parent + node = node.Parent() } return node != nil && node.Kind == ast.KindDecorator } diff --git a/tsc/internal/format/scanner.go b/tsc/internal/format/scanner.go index d1ac0882ea150..63a74def87534 100644 --- a/tsc/internal/format/scanner.go +++ b/tsc/internal/format/scanner.go @@ -109,8 +109,8 @@ func shouldRescanGreaterThanToken(node *ast.Node) bool { } func shouldRescanJsxIdentifier(node *ast.Node) bool { - if node.Parent != nil { - switch node.Parent.Kind { + if node.Parent() != nil { + switch node.Parent().Kind { case ast.KindJsxAttribute, ast.KindJsxOpeningElement, ast.KindJsxClosingElement, @@ -129,11 +129,11 @@ func shouldRescanJsxIdentifier(node *ast.Node) bool { func isLeftmostJsxTagName(node *ast.Node) bool { return ast.FindAncestorOrQuit(node, func(n *ast.Node) ast.FindAncestorResult { switch { - case n.Parent == nil: + case n.Parent() == nil: return ast.FindAncestorQuit case ast.IsJsxTagName(n): return ast.FindAncestorTrue - case ast.IsPropertyAccessExpression(n.Parent) && n.Parent.Expression() == n: + case ast.IsPropertyAccessExpression(n.Parent()) && n.Parent().Expression() == n: return ast.FindAncestorFalse default: return ast.FindAncestorQuit @@ -162,7 +162,7 @@ func shouldRescanTemplateToken(container *ast.Node) bool { } func shouldRescanJsxAttributeValue(node *ast.Node) bool { - return node.Parent != nil && ast.IsJsxAttribute(node.Parent) && node.Parent.Initializer() == node + return node.Parent() != nil && ast.IsJsxAttribute(node.Parent()) && node.Parent().Initializer() == node } func startsWithSlashToken(t ast.Kind) bool { diff --git a/tsc/internal/format/span.go b/tsc/internal/format/span.go index df9d11119b2cb..3c8fcde05fa34 100644 --- a/tsc/internal/format/span.go +++ b/tsc/internal/format/span.go @@ -101,7 +101,7 @@ func getOwnOrInheritedDelta(n *ast.Node, options lsutil.FormatCodeSettings, sour previousLine = line child = n - n = n.Parent + n = n.Parent() } return 0 } @@ -309,7 +309,7 @@ func (w *formatSpanWorker) execute(s *formattingScanner) []core.TextChange { // pair here, we're already done and we can ignore it. parent := astnav.FindPrecedingToken(w.sourceFile, tokenInfo.Loc.End()) if parent != nil { - parent = parent.Parent + parent = parent.Parent() } if parent == nil { parent = w.previousParent @@ -1233,7 +1233,7 @@ func getFirstNonDecoratorTokenOfNode(node *ast.Node) ast.Kind { case ast.KindSetAccessor: return ast.KindSetKeyword case ast.KindMethodDeclaration: - if node.AsMethodDeclaration().AsteriskToken != nil { + if node.AsMethodDeclaration().AsteriskToken() != nil { return ast.KindAsteriskToken } fallthrough diff --git a/tsc/internal/format/util.go b/tsc/internal/format/util.go index 2b562d15d66d7..1d8b53092b5f4 100644 --- a/tsc/internal/format/util.go +++ b/tsc/internal/format/util.go @@ -107,10 +107,10 @@ func findImmediatelyPrecedingTokenOfKind(end int, expectedTokenKind ast.Kind, so func findOutermostNodeWithinListLevel(node *ast.Node) *ast.Node { current := node for current != nil && - current.Parent != nil && - current.Parent.End() == node.End() && - !isListElement(current.Parent, current) { - current = current.Parent + current.Parent() != nil && + current.Parent().End() == node.End() && + !isListElement(current.Parent(), current) { + current = current.Parent() } return current @@ -128,7 +128,7 @@ func isListElement(parent *ast.Node, node *ast.Node) bool { case ast.KindSourceFile, ast.KindBlock, ast.KindModuleBlock: return node.Loc.ContainedBy(parent.StatementList().Loc) case ast.KindCatchClause: - return node.Loc.ContainedBy(parent.AsCatchClause().Block.StatementList().Loc) + return node.Loc.ContainedBy(parent.AsCatchClause().Block().StatementList().Loc) } return false diff --git a/tsc/internal/linkarena/heap_linux.go b/tsc/internal/linkarena/heap_linux.go new file mode 100644 index 0000000000000..81247318e6e2f --- /dev/null +++ b/tsc/internal/linkarena/heap_linux.go @@ -0,0 +1,31 @@ +package linkarena + +import ( + "os" + "strconv" + "strings" +) + +// sysGoHeapRanges returns the address ranges that the Go runtime has set aside for its heap. +// The runtime names its mappings, whi ch the kernel reports when it supports naming anonymous +// memory; without that support the result is empty. Only Verify uses this. +func sysGoHeapRanges() []addrRange { + maps, err := os.ReadFile("/proc/self/maps") //nolint:forbidigo + if err != nil { + return nil + } + var ranges []addrRange + for line := range strings.Lines(string(maps)) { + if !strings.Contains(line, "[anon: Go: heap") { + continue + } + addresses, _, _ := strings.Cut(line, " ") + lo, hi, _ := strings.Cut(addresses, "-") + start, err1 := strconv.ParseUint(lo, 16, 64) + end, err2 := strconv.ParseUint(hi, 16, 64) + if err1 == nil && err2 == nil { + ranges = append(ranges, addrRange{lo: uintptr(start), hi: uintptr(end)}) + } + } + return ranges +} diff --git a/tsc/internal/linkarena/heap_other.go b/tsc/internal/linkarena/heap_other.go new file mode 100644 index 0000000000000..3dd732ff67abd --- /dev/null +++ b/tsc/internal/linkarena/heap_other.go @@ -0,0 +1,5 @@ +//go:build !linux + +package linkarena + +func sysGoHeapRanges() []addrRange { return nil } diff --git a/tsc/internal/linkarena/linkarena.go b/tsc/internal/linkarena/linkarena.go new file mode 100644 index 0000000000000..e92fd0eba159d --- /dev/null +++ b/tsc/internal/linkarena/linkarena.go @@ -0,0 +1,444 @@ +// Package linkarena allocates memory for objects that refer to each other through 32-bit +// links instead of pointers. +// +// An Arena hands out memory from chunks. A chunk is an ordinary Go allocation of one or +// more 8 KiB pages whose contents the garbage collector treats as plain bytes: apart from +// one pointer back to the arena, nothing stored in a chunk is scanned. Every page has a +// number, and a process-wide table maps page numbers to page addresses. A [Link] is a page +// number together with a position inside that page; see [At] and [LinkTo]. +// +// Lifetimes are managed by the garbage collector. A pointer into arena memory keeps its +// chunk alive, the chunk keeps its arena alive, and the arena keeps all of its chunks alive, +// so everything allocated from one arena lives as long as any part of it is referenced. +// The page table holds plain addresses and keeps nothing alive; when a chunk is collected +// its page numbers are reused. +// +// Because the collector does not look inside chunks, whatever is stored there does not keep +// its target alive. Callers must uphold two rules: +// +// - A pointer to memory outside arenas (a string, a slice, any Go object) that is stored +// in arena memory must be registered with [Arena.Keep], unless something else is +// guaranteed to keep the target alive for as long as the arena. +// - A link or pointer from one arena into another must be recorded, so that the first +// arena keeps the second alive. [LinkTo] does this for links; [Refer] does it for +// pointers. +// +// Setting the TSGO_ASTVERIFY environment variable to 1 makes arenas record the type of every +// allocation so that [Arena.Verify] can check both rules. +package linkarena + +import ( + "os" + "reflect" + "runtime" + "slices" + "sync" + "sync/atomic" + "unsafe" +) + +const ( + pageShift = 13 + // The size of a page of the Go allocator. An allocation that fills a whole number of + // these pages starts at a page boundary, or a fixed 8 bytes after it when the allocator + // puts a header of its own in front. That is what lets the page header of any object be + // found from its address; newChunk checks it for every chunk. + pageSize = 1 << pageShift + pageMask = pageSize - 1 + + // Positions inside a page are counted in units of 8 bytes. + unitShift = 3 + offsetBits = pageShift - unitShift + offsetMask = 1<>offsetBits]))) + return unsafe.Add(page, uintptr(l&offsetMask)<= maxPages || atomic.LoadUintptr(&pages[id]) != uintptr(unsafe.Pointer(h)) { + panic("linkarena: pointer to memory that was not allocated from an arena") + } + return h +} + +// Of returns the arena that p was allocated from. It panics when p is not arena memory. +func Of(p unsafe.Pointer) *Arena { + return checkedPageOf(p).arena +} + +// LinkTo returns a link to target for storing in the memory at holder. Both must be arena +// memory. When they belong to different arenas, holder's arena is made to keep target's +// arena alive. +func LinkTo(holder unsafe.Pointer, target unsafe.Pointer) Link { + if target == nil { + return 0 + } + t := checkedPageOf(target) + if h := pageOf(holder); h.arena != t.arena { + checkedPageOf(holder).arena.use(t.arena) + } + return Link(t.id<>unitShift) +} + +// Refer records that the memory at holder contains a pointer to target. Both must be arena +// memory. When they belong to different arenas, holder's arena is made to keep target's +// arena alive. +func Refer(holder unsafe.Pointer, target unsafe.Pointer) { + if h, t := pageOf(holder), pageOf(target); h.arena != t.arena { + checkedPageOf(holder).arena.use(checkedPageOf(target).arena) + } +} + +// Arena allocates memory that is released as a whole once nothing refers to any of it. +// Allocation is not safe for concurrent use; Keep and the recording of references between +// arenas are. +type Arena struct { + // The page being allocated from and the number of bytes used in it. + page unsafe.Pointer + used uintptr + // The chunk that page belongs to. + chunkBase unsafe.Pointer + chunkSize uintptr + pagesLeft int + // The number of bytes the owner still expects to allocate, used to size chunks. + hint int + // The number of pages in the most recent chunk allocated beyond the hint. + grown int + + // Every chunk of the arena, and their address ranges in sorted order. + chunks []unsafe.Pointer + ranges []addrRange + size int + + mu sync.Mutex + // Objects outside arenas that this arena's memory points to. + kept []unsafe.Pointer + lastKept atomic.Uintptr + // Arenas that this arena's memory points into. + uses map[*Arena]struct{} + lastUse atomic.Pointer[Arena] + + verify *verifyState +} + +// NewArena creates an arena. sizeHint is the number of bytes the caller expects to allocate, +// or zero when it does not know. +func NewArena(sizeHint int) *Arena { + a := &Arena{used: pageEnd, hint: sizeHint} + if verifying { + a.verify = &verifyState{} + } + return a +} + +// Alloc returns size bytes of zeroed memory aligned to 8 bytes. size must not exceed +// MaxAlloc. +func (a *Arena) Alloc(size uintptr) unsafe.Pointer { + return a.allocAligned((size + 7) &^ 7) +} + +// MaxAlloc is the largest size Alloc accepts. +const MaxAlloc = maxAlloc + +func (a *Arena) allocAligned(size uintptr) unsafe.Pointer { + used := a.used + if end := used + size; end <= pageEnd { + a.used = end + return unsafe.Add(a.page, used) + } + return a.allocSlow(size) +} + +func (a *Arena) allocSlow(size uintptr) unsafe.Pointer { + if size > maxAlloc { + panic("linkarena: allocation does not fit in a page") + } + if a.pagesLeft > 0 { + a.page = unsafe.Add(a.page, pageSize) + a.pagesLeft-- + } else { + a.grow() + } + a.used = headerSize + size + return unsafe.Add(a.page, headerSize) +} + +// grow adds a chunk to the arena. +func (a *Arena) grow() { + // Chunks are as large as the owner's estimate allows, so that little is left unused when + // the estimate is right. Beyond the estimate, chunk sizes double. + n := 1 + if a.hint >= pageSize { + n = min(a.hint>>pageShift, maxChunkPages) + n = 1 << (bitLen(uint(n)) - 1) + } else { + if a.grown > 0 { + n = min(a.grown*2, maxChunkPages) + } + a.grown = n + } + a.hint -= n << pageShift + base := newChunk(a, n) + a.chunks = append(a.chunks, base) + r := addrRange{lo: uintptr(base), hi: uintptr(base) + uintptr(n)<>= 1 { + n++ + } + return n +} + +// chunk is the Go object behind a chunk of n pages: two pointers to the arena followed by +// plain bytes, n*pageSize-8 bytes in all. The allocator places such an object either at a +// page boundary or, when it prepends an 8-byte header of its own, 8 bytes after one. Either +// way the chunk covers n pages from that boundary except for the last word, and one of the +// two pointers lands in pageHeader.arena of the first page. +type chunk[B any] struct { + arena0, arena1 *Arena + _ B +} + +// newChunk allocates a chunk of n pages for a, numbers its pages and returns the address of +// its first page. +func newChunk(a *Arena, n int) unsafe.Pointer { + switch n { + case 1: + return initChunk(new(chunk[[1*pageSize - 24]byte]), a, n) + case 2: + return initChunk(new(chunk[[2*pageSize - 24]byte]), a, n) + case 4: + return initChunk(new(chunk[[4*pageSize - 24]byte]), a, n) + case 8: + return initChunk(new(chunk[[8*pageSize - 24]byte]), a, n) + } + panic("linkarena: unsupported chunk size") +} + +type pageIDs struct { + n int + ids [maxChunkPages]uint32 +} + +func initChunk[B any](c *chunk[B], a *Arena, n int) unsafe.Pointer { + offset := uintptr(unsafe.Pointer(c)) & pageMask + if offset != 0 && offset != 8 { + // Links are computed from addresses on the assumption stated at pageSize. + panic("linkarena: the Go allocator placed a chunk where its pages cannot be found") + } + base := unsafe.Add(unsafe.Pointer(c), -int(offset)) + c.arena0, c.arena1 = a, a + ids := pageIDs{n: n} + mu.Lock() + for i := range n { + if k := len(freePageIDs); k > 0 { + ids.ids[i] = freePageIDs[k-1] + freePageIDs = freePageIDs[:k-1] + } else { + if nextPageID == maxPages { + mu.Unlock() + panic("linkarena: more than 32 GiB of arena memory is in use") + } + ids.ids[i] = nextPageID + nextPageID++ + } + } + mu.Unlock() + for i := range n { + h := (*pageHeader)(unsafe.Add(base, i< 0 { + // Not a pointer the collector sees: past its first words the chunk is plain bytes. + *(*uintptr)(unsafe.Pointer(&h.arena)) = uintptr(unsafe.Pointer(a)) + } + h.id = ids.ids[i] + atomic.StoreUintptr(&pages[ids.ids[i]], uintptr(unsafe.Pointer(h))) + } + // Runs once the chunk has been collected, when no link into it can be followed any more. + runtime.AddCleanup(c, releasePages, ids) + return base +} + +func releasePages(ids pageIDs) { + for _, id := range ids.ids[:ids.n] { + atomic.StoreUintptr(&pages[id], 0) + } + mu.Lock() + freePageIDs = append(freePageIDs, ids.ids[:ids.n]...) + mu.Unlock() +} + +// Size returns the number of bytes of chunks the arena holds. +func (a *Arena) Size() int { + return a.size +} + +// Contains reports whether p points into the arena's memory. +func (a *Arena) Contains(p unsafe.Pointer) bool { + addr := uintptr(p) + return addr-uintptr(a.chunkBase) < a.chunkSize || inRanges(a.ranges, addr) +} + +type addrRange struct { + lo, hi uintptr +} + +func compareRanges(a, b addrRange) int { + switch { + case a.lo < b.lo: + return -1 + case a.lo > b.lo: + return 1 + } + return 0 +} + +// inRanges reports whether addr lies in one of the sorted, disjoint ranges. +func inRanges(ranges []addrRange, addr uintptr) bool { + i, found := slices.BinarySearchFunc(ranges, addrRange{lo: addr}, compareRanges) + return found || i > 0 && addr < ranges[i-1].hi +} + +// Keep keeps the object that p points into alive for as long as the arena. size is the +// number of bytes at p that arena memory may point into; it is only used by Verify. Keep is +// safe for concurrent use. +func (a *Arena) Keep(p unsafe.Pointer, size uintptr) { + if p == nil || a.lastKept.Load() == uintptr(p) { + return + } + a.mu.Lock() + a.kept = append(a.kept, p) + a.lastKept.Store(uintptr(p)) + if a.verify != nil { + a.verify.kept = append(a.verify.kept, addrRange{lo: uintptr(p), hi: uintptr(p) + max(size, 1)}) + } + a.mu.Unlock() +} + +// KeepSlice keeps the backing array of s alive for as long as the arena. +func KeepSlice[T any](a *Arena, s []T) { + if cap(s) != 0 { + a.Keep(unsafe.Pointer(unsafe.SliceData(s)), uintptr(cap(s))*unsafe.Sizeof(s[0])) + } +} + +// Use makes the arena keep the arena that holds target alive. target must be arena memory. +func (a *Arena) Use(target unsafe.Pointer) { + if b := pageOf(target).arena; b != a { + a.use(checkedPageOf(target).arena) + } +} + +func (a *Arena) use(b *Arena) { + if a == b || a.lastUse.Load() == b { + return + } + a.mu.Lock() + if _, ok := a.uses[b]; !ok { + if a.uses == nil { + a.uses = make(map[*Arena]struct{}) + } + a.uses[b] = struct{}{} + } + a.lastUse.Store(b) + a.mu.Unlock() +} + +// New allocates a zeroed T in the arena. +func New[T any](a *Arena) *T { + var zero T + p := a.allocAligned((unsafe.Sizeof(zero) + 7) &^ 7) + if a.verify != nil { + a.verify.record(p, reflect.TypeFor[T](), 1) + } + return (*T)(p) +} + +// MakeSlice allocates a zeroed slice with the given length and capacity. A slice that does +// not fit in a page is allocated outside the arena and kept alive by it. +func MakeSlice[T any](a *Arena, length int, capacity int) []T { + if capacity == 0 { + return nil + } + var zero T + size := unsafe.Sizeof(zero) * uintptr(capacity) + if size > maxAlloc { + s := make([]T, length, capacity) + KeepSlice(a, s) + return s + } + p := a.allocAligned((size + 7) &^ 7) + if a.verify != nil { + a.verify.record(p, reflect.TypeFor[T](), capacity) + } + return unsafe.Slice((*T)(p), capacity)[:length] +} diff --git a/tsc/internal/linkarena/linkarena_test.go b/tsc/internal/linkarena/linkarena_test.go new file mode 100644 index 0000000000000..403632c4209aa --- /dev/null +++ b/tsc/internal/linkarena/linkarena_test.go @@ -0,0 +1,284 @@ +package linkarena + +import ( + "runtime" + "sync/atomic" + "testing" + "time" + "unsafe" + + "gotest.tools/v3/assert" +) + +type testNode struct { + parent *testNode + child Link + text string + list []*testNode + value int +} + +func (n *testNode) setChild(c *testNode) { n.child = LinkTo(unsafe.Pointer(n), unsafe.Pointer(c)) } +func (n *testNode) getChild() *testNode { return (*testNode)(At(n.child)) } + +func collect() { + for range 3 { + runtime.GC() + } +} + +func eventually(t *testing.T, what string, done func() bool) { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for !done() { + if time.Now().After(deadline) { + t.Fatal(what) + } + runtime.GC() + time.Sleep(time.Millisecond) + } +} + +func TestChunksArePageAligned(t *testing.T) { + t.Parallel() + // The assumption the whole package rests on; see pageSize. + a := NewArena(0) + for range 200 { + a.grow() + } + sizes := map[uintptr]bool{} + for _, r := range a.ranges { + assert.Equal(t, r.lo&pageMask, uintptr(0)) + sizes[r.hi-r.lo] = true + } + assert.Equal(t, len(sizes), 4) +} + +func TestAlloc(t *testing.T) { + t.Parallel() + a := NewArena(0) + var previous unsafe.Pointer + for _, size := range []uintptr{1, 8, 24, 100, 4000, 4000, 4000, MaxAlloc, 40} { + p := a.Alloc(size) + assert.Assert(t, p != previous) + assert.Equal(t, uintptr(p)%8, uintptr(0)) + assert.Assert(t, uintptr(p)&pageMask >= headerSize) + assert.Assert(t, uintptr(p)&pageMask+size <= pageEnd, "allocation crosses a page") + assert.Assert(t, a.Contains(p)) + assert.Assert(t, a.Contains(unsafe.Add(p, size-1))) + assert.Equal(t, Of(p), a) + b := unsafe.Slice((*byte)(p), size) + for _, v := range b { + assert.Equal(t, v, byte(0)) + } + for i := range b { + b[i] = 0xff + } + previous = p + } + // Page headers survive allocations that fill their pages. + for _, r := range a.ranges { + for page := r.lo; page < r.hi; page += pageSize { + assert.Equal(t, atomic.LoadUintptr(&pages[(*pageHeader)(*(*unsafe.Pointer)(unsafe.Pointer(&page))).id]), page) + } + } + onHeap := new(testNode) + assert.Assert(t, !a.Contains(unsafe.Pointer(onHeap))) + assert.Assert(t, MakeSlice[int](a, 0, 0) == nil) + runtime.KeepAlive(a) +} + +func TestChunkSizes(t *testing.T) { + t.Parallel() + sizeAfter := func(hint int, allocated int) int { + a := NewArena(hint) + for n := 0; n < allocated; n += 64 { + a.Alloc(64) + } + return a.Size() + } + // Without an estimate chunks double; with one, little is left unused when it was right. + assert.Equal(t, sizeAfter(0, 64), pageSize) + assert.Assert(t, sizeAfter(0, 1<<20) < 1<<20+1<<17) + for _, hint := range []int{3000, 20000, 100000, 1 << 20} { + size := sizeAfter(hint, hint) + assert.Assert(t, size < hint+hint/50+2*pageSize, "hint %d: %d bytes of chunks", hint, size) + } +} + +func TestLinks(t *testing.T) { + t.Parallel() + a := NewArena(0) + root := New[testNode](a) + node := root + const count = 20000 + for i := 1; i <= count; i++ { + next := New[testNode](a) + next.value = i + node.setChild(next) + node = next + } + assert.Assert(t, len(a.chunks) > 4) + n := 0 + for node = root; node != nil; node = node.getChild() { + assert.Equal(t, node.value, n) + assert.Equal(t, Of(unsafe.Pointer(node)), a) + n++ + } + assert.Equal(t, n, count+1) + assert.Assert(t, At(0) == nil) + assert.Equal(t, LinkTo(unsafe.Pointer(root), nil), Link(0)) + + list := MakeSlice[*testNode](a, 0, 4) + list = append(list, root) + assert.Assert(t, a.Contains(unsafe.Pointer(unsafe.SliceData(list)))) + big := MakeSlice[*testNode](a, 2000, 2000) + assert.Assert(t, !a.Contains(unsafe.Pointer(unsafe.SliceData(big)))) + runtime.KeepAlive(a) +} + +func TestNotArenaMemory(t *testing.T) { + t.Parallel() + if raceEnabled { + t.Skip("the pointer checker stops the process before the package can panic") + } + a := NewArena(0) + node := New[testNode](a) + onHeap := new([4 * pageSize]byte) + check := func(f func()) { + defer func() { assert.Assert(t, recover() != nil) }() + f() + } + check(func() { LinkTo(unsafe.Pointer(node), unsafe.Pointer(&onHeap[2*pageSize+64])) }) + check(func() { Of(unsafe.Pointer(&onHeap[2*pageSize+64])) }) + check(func() { a.Alloc(MaxAlloc + 1) }) +} + +// build returns a pointer into the middle of a two-arena structure and nothing else. +// +//go:noinline +func build(freed chan<- string) *testNode { + a, b := NewArena(0), NewArena(0) + root := New[testNode](a) + node := root + for range 3000 { + next := New[testNode](a) + node.setChild(next) + node = next + } + other := New[testNode](b) + other.value = 42 + node.setChild(other) + + kept, lost := &testNode{value: 1}, &testNode{value: 2} + runtime.SetFinalizer(kept, func(*testNode) { freed <- "kept" }) + runtime.SetFinalizer(lost, func(*testNode) { freed <- "lost" }) + root.parent = kept + a.Keep(unsafe.Pointer(kept), unsafe.Sizeof(*kept)) + root.list = MakeSlice[*testNode](a, 1, 1) + root.list[0] = lost + return root.getChild().getChild() +} + +func TestLifetime(t *testing.T) { + t.Parallel() + freed := make(chan string, 2) + // The only reference to the arenas is the node pointer inside this function. + firstPage := func() uint32 { + node := build(freed) + + // The collector does not look inside chunks, so only the registered object survives. + collect() + select { + case name := <-freed: + assert.Equal(t, name, "lost") + case <-time.After(10 * time.Second): + t.Fatal("the unregistered object was not collected") + } + // One pointer into the arena keeps all of it alive, along with the arena it links + // into and the object it keeps. + collect() + assert.Equal(t, len(freed), 0) + steps := 0 + last := node + for n := node; n != nil; n = n.getChild() { + last = n + steps++ + } + assert.Equal(t, steps, 3000) + assert.Equal(t, last.value, 42) + return pageOf(unsafe.Pointer(node)).id + }() + + // Once nothing points into the arena, everything goes, and the page numbers are free. + eventually(t, "the kept object was not released", func() bool { return len(freed) == 1 }) + assert.Equal(t, <-freed, "kept") + eventually(t, "the page number was not released", func() bool { return atomic.LoadUintptr(&pages[firstPage]) == 0 }) +} + +func TestVerify(t *testing.T) { + t.Parallel() + a, b, c := NewArena(0), NewArena(0), NewArena(0) + for _, arena := range []*Arena{a, b, c} { + arena.verify = &verifyState{} + } + alloc := func(arena *Arena) *testNode { return New[testNode](arena) } + problems := func() []string { + var result []string + for _, v := range a.Verify(10) { + result = append(result, v.Field+": "+v.Problem) + } + return result + } + + node, child := alloc(a), alloc(a) + node.setChild(child) + child.parent = node + child.text = "static" + node.list = MakeSlice[*testNode](a, 1, 2) + node.list[0] = child + assert.Equal(t, len(problems()), 0) + + // A link into another arena is recorded by LinkTo, a pointer is not. + inB, inC := alloc(b), alloc(c) + child.setChild(inB) + assert.Equal(t, len(problems()), 0) + child.parent = inC + if CanFindGoHeapPointers() { + assert.DeepEqual(t, problems(), []string{".parent: a pointer to Go memory that this arena does not keep alive"}) + } + Refer(unsafe.Pointer(child), unsafe.Pointer(inC)) + assert.Equal(t, len(problems()), 0) + + // A link whose page is gone, and a link into an arena that is not kept alive. + saved := child.child + child.child = Link(maxPages-1) << offsetBits + assert.DeepEqual(t, problems(), []string{".child: a link to a page that is not in use"}) + d := NewArena(0) + child.child = Link(pageOf(unsafe.Pointer(New[testNode](d))).id<>offsetBits]) + if page == 0 { + problem = "a link to a page that is not in use" + } else if !inRanges(reachable, page) { + problem = "a link into an arena that this one does not keep alive" + } + case !inRanges(reachable, target) && !inRanges(kept, target) && inRanges(heap, target): + // Either an ordinary Go object or memory of another arena. + problem = "a pointer to Go memory that this arena does not keep alive" + } + if problem == "" { + continue + } + violations = append(violations, Violation{Type: alloc.typ, Field: slot.path, Addr: elem, Target: target, Problem: problem}) + if len(violations) >= limit { + return violations + } + } + } + } + return violations +} + +// CanFindGoHeapPointers reports whether Verify can recognize pointers to Go memory that an +// arena does not keep alive. +func CanFindGoHeapPointers() bool { + return len(sysGoHeapRanges()) > 0 +} + +type slotKind uint8 + +const ( + slotPointer slotKind = iota + slotString + slotSlice + slotInterface + slotLink +) + +type referenceSlot struct { + offset uintptr + kind slotKind + path string +} + +// read returns the reference stored in the slot of the value at addr. ok is false when the +// slot holds no reference (an empty string or a slice without capacity). +func (s referenceSlot) read(addr uintptr) (target uintptr, ok bool) { + p := *(*unsafe.Pointer)(unsafe.Pointer(&addr)) + p = unsafe.Add(p, s.offset) + switch s.kind { + case slotLink: + return uintptr(*(*Link)(p)), true + case slotString: + words := (*[2]uintptr)(p) + return words[0], words[1] != 0 + case slotSlice: + words := (*[3]uintptr)(p) + return words[0], words[2] != 0 + case slotInterface: + return (*[2]uintptr)(p)[1], true + } + return *(*uintptr)(p), true +} + +var ( + slotCache sync.Map // reflect.Type -> []referenceSlot + linkType = reflect.TypeFor[Link]() +) + +func referenceSlots(t reflect.Type) []referenceSlot { + if cached, ok := slotCache.Load(t); ok { + return cached.([]referenceSlot) + } + slots := appendReferenceSlots(nil, t, 0, "") + slotCache.Store(t, slots) + return slots +} + +func appendReferenceSlots(slots []referenceSlot, t reflect.Type, offset uintptr, path string) []referenceSlot { + if t == linkType { + return append(slots, referenceSlot{offset: offset, kind: slotLink, path: path}) + } + switch t.Kind() { + case reflect.Pointer, reflect.UnsafePointer, reflect.Map, reflect.Chan, reflect.Func: + return append(slots, referenceSlot{offset: offset, kind: slotPointer, path: path}) + case reflect.String: + return append(slots, referenceSlot{offset: offset, kind: slotString, path: path}) + case reflect.Slice: + return append(slots, referenceSlot{offset: offset, kind: slotSlice, path: path}) + case reflect.Interface: + return append(slots, referenceSlot{offset: offset, kind: slotInterface, path: path}) + case reflect.Struct: + for f := range t.Fields() { + slots = appendReferenceSlots(slots, f.Type, offset+f.Offset, path+"."+f.Name) + } + case reflect.Array: + for i := range t.Len() { + slots = appendReferenceSlots(slots, t.Elem(), offset+uintptr(i)*t.Elem().Size(), fmt.Sprintf("%s[%d]", path, i)) + } + } + return slots +} diff --git a/tsc/internal/ls/autoimport/extract.go b/tsc/internal/ls/autoimport/extract.go index 08a5a5b459857..d9e7fbbe4177d 100644 --- a/tsc/internal/ls/autoimport/extract.go +++ b/tsc/internal/ls/autoimport/extract.go @@ -136,7 +136,7 @@ func isNonPatternAmbientModuleDeclaration(file *ast.SourceFile, decl *ast.Module func (e *exportExtractor) extractFromModule(file *ast.SourceFile) []*Export { moduleAugmentations := core.MapNonNil(file.ModuleAugmentations, func(name *ast.ModuleName) *ast.ModuleDeclaration { - decl := name.Parent + decl := name.Parent() if ast.IsGlobalScopeAugmentation(decl) { return nil } @@ -243,13 +243,13 @@ func (e *symbolExtractor) extractFromSymbol(name string, symbol *ast.Symbol, mod } } } else if syntax == ExportSyntaxCommonJSModuleExports { - expression := symbol.Declarations[0].AsBinaryExpression().Right + expression := symbol.Declarations[0].AsBinaryExpression().Right() if expression.Kind == ast.KindObjectLiteralExpression { // what is actually desirable here? I think it would be reasonable to only treat these as exports // if *every* property is a shorthand property or identifier: identifier // At least, it would be sketchy if there were any methods, computed properties... - *exports = slices.Grow(*exports, len(expression.AsObjectLiteralExpression().Properties.Nodes)) - for _, prop := range expression.AsObjectLiteralExpression().Properties.Nodes { + *exports = slices.Grow(*exports, len(expression.AsObjectLiteralExpression().Properties().Nodes)) + for _, prop := range expression.AsObjectLiteralExpression().Properties().Nodes { if ast.IsShorthandPropertyAssignment(prop) || ast.IsPropertyAssignment(prop) && prop.AsPropertyAssignment().Name().Kind == ast.KindIdentifier { export, _ := e.createExport(expression.Symbol().Members[prop.Name().Text()], moduleID, moduleFileName, syntax, file, checkerLease) if export != nil { @@ -378,7 +378,7 @@ func (e *symbolExtractor) tryResolveSymbol(symbol *ast.Symbol, syntax ExportSynt switch syntax { case ExportSyntaxNamed: decl := ast.GetDeclarationOfKind(symbol, ast.KindExportSpecifier) - if decl.Parent.Parent.AsExportDeclaration().ModuleSpecifier == nil { + if decl.Parent().Parent().AsExportDeclaration().ModuleSpecifier() == nil { if n := core.FirstNonZero(decl.Name(), decl.PropertyName()); n.Kind == ast.KindIdentifier { loc = n name = n.Text() diff --git a/tsc/internal/ls/autoimport/fix.go b/tsc/internal/ls/autoimport/fix.go index 76d8498e6fc7b..ac5a0eb55bf9f 100644 --- a/tsc/internal/ls/autoimport/fix.go +++ b/tsc/internal/ls/autoimport/fix.go @@ -111,7 +111,7 @@ func (f *Fix) Edits( case lsproto.AutoImportFixKindPromoteTypeOnly: promotedDeclaration := promoteFromTypeOnly(tracker, f.TypeOnlyAliasDeclaration, compilerOptions, file, preferences) if promotedDeclaration.Kind == ast.KindImportSpecifier { - moduleSpec := getModuleSpecifierText(promotedDeclaration.Parent.Parent) + moduleSpec := getModuleSpecifierText(promotedDeclaration.Parent().Parent()) edits, safe := fileEdits(tracker, file) return edits, diagnostics.Remove_type_from_import_of_0_from_1.Localize(locale, f.Name, moduleSpec), safe } @@ -175,10 +175,10 @@ func getAddToExistingImportFix(file *ast.SourceFile, fix *Fix) *addToExistingImp panic("expected import clause") } case ast.KindCallExpression: - if !ast.IsVariableDeclarationInitializedToRequire(importNode.Parent) { + if !ast.IsVariableDeclarationInitializedToRequire(importNode.Parent()) { panic("expected require call expression to be in variable declaration") } - importClauseOrBindingPattern = importNode.Parent.Name() + importClauseOrBindingPattern = importNode.Parent().Name() if importClauseOrBindingPattern == nil || !ast.IsObjectBindingPattern(importClauseOrBindingPattern) { panic("expected object binding pattern in variable declaration") } @@ -225,8 +225,8 @@ func addToExistingImport( }) var existingSpecifiers []*ast.Node - if importClause.NamedBindings != nil && importClause.NamedBindings.Kind == ast.KindNamedImports { - existingSpecifiers = importClause.NamedBindings.Elements() + if importClause.NamedBindings() != nil && importClause.NamedBindings().Kind == ast.KindNamedImports { + existingSpecifiers = importClause.NamedBindings().Elements() } if defaultImport != nil { @@ -235,7 +235,7 @@ func addToExistingImport( } if len(namedImports) > 0 { - specifierComparer, isSorted := lsutil.GetNamedImportSpecifierComparerWithDetection(importClause.Parent, file, preferences) + specifierComparer, isSorted := lsutil.GetNamedImportSpecifierComparerWithDetection(importClause.Parent(), file, preferences) newSpecifiers := core.Map(namedImports, func(namedImport *newImportBinding) *ast.Node { var identifier *ast.Node if namedImport.propertyName != "" { @@ -262,8 +262,8 @@ func addToExistingImport( specsToCompareAgainst = core.Map(existingSpecifiers, func(e *ast.Node) *ast.Node { spec := e.AsImportSpecifier() var propertyName *ast.Node - if spec.PropertyName != nil { - propertyName = spec.PropertyName + if spec.PropertyName() != nil { + propertyName = spec.PropertyName() } syntheticSpec := ct.NodeFactory.NewImportSpecifier( true, // isTypeOnly @@ -276,7 +276,7 @@ func addToExistingImport( for _, spec := range newSpecifiers { insertionIndex := lsutil.GetImportSpecifierInsertionIndex(specsToCompareAgainst, spec, specifierComparer) - ct.InsertImportSpecifierAtIndex(file, spec, importClause.NamedBindings, insertionIndex) + ct.InsertImportSpecifierAtIndex(file, spec, importClause.NamedBindings(), insertionIndex) } } else if len(existingSpecifiers) > 0 { for _, spec := range newSpecifiers { @@ -285,8 +285,8 @@ func addToExistingImport( } else { if len(newSpecifiers) > 0 { namedImports := ct.NodeFactory.NewNamedImports(ct.NodeFactory.NewNodeList(newSpecifiers)) - if importClause.NamedBindings != nil { - ct.ReplaceNode(file, importClause.NamedBindings, namedImports, nil) + if importClause.NamedBindings() != nil { + ct.ReplaceNode(file, importClause.NamedBindings(), namedImports, nil) } else { if importClause.Name() == nil { panic("Import clause must have either named imports or a default import") @@ -336,8 +336,8 @@ func addElementToBindingPattern( propertyName string, ) { element := ct.NodeFactory.NewBindingElement(nil, nil, ct.NodeFactory.NewIdentifier(name), core.IfElse(propertyName == "", nil, ct.NodeFactory.NewIdentifier(propertyName))) - if len(bindingPattern.Elements.Nodes) > 0 { - ct.InsertNodeInListAfter(file, bindingPattern.Elements.Nodes[len(bindingPattern.Elements.Nodes)-1], element, bindingPattern.Elements) + if len(bindingPattern.Elements().Nodes) > 0 { + ct.InsertNodeInListAfter(file, bindingPattern.Elements().Nodes[len(bindingPattern.Elements().Nodes)-1], element, bindingPattern.Elements()) } else { ct.ReplaceNode(file, bindingPattern.AsNode(), ct.NodeFactory.NewBindingPattern(ast.KindObjectBindingPattern, ct.AsNodeFactory().NewNodeList([]*ast.Node{element})), nil) } @@ -678,8 +678,8 @@ func getNamespaceLikeImportText(declaration *ast.Node) string { return declaration.Name().Text() case ast.KindJSDocImportTag, ast.KindImportDeclaration: importClause := declaration.ImportClause() - if importClause != nil && importClause.AsImportClause().NamedBindings != nil && importClause.AsImportClause().NamedBindings.Kind == ast.KindNamespaceImport { - return importClause.AsImportClause().NamedBindings.Name().Text() + if importClause != nil && importClause.AsImportClause().NamedBindings() != nil && importClause.AsImportClause().NamedBindings().Kind == ast.KindNamespaceImport { + return importClause.AsImportClause().NamedBindings().Name().Text() } return "" default: @@ -752,7 +752,7 @@ func (v *View) tryAddToExistingImport( continue } - namedBindings := importClause.NamedBindings + namedBindings := importClause.NamedBindings() // A type-only import may not have both a default and named imports, so the only way a name can // be added to an existing type-only import is adding a named import to existing named bindings. if importClause.IsTypeOnly() && !(importKind == lsproto.ImportKindNamed && namedBindings != nil) { @@ -822,7 +822,7 @@ func getImportKind(importingFile *ast.SourceFile, export *Export, program *compi // !!! cache this? for _, statement := range importingFile.Statements.Nodes { // `import foo` parses as an ImportEqualsDeclaration even though it could be an ImportDeclaration - if ast.IsImportEqualsDeclaration(statement) && !ast.NodeIsMissing(statement.AsImportEqualsDeclaration().ModuleReference) { + if ast.IsImportEqualsDeclaration(statement) && !ast.NodeIsMissing(statement.AsImportEqualsDeclaration().ModuleReference()) { return lsproto.ImportKindCommonJS } } @@ -857,10 +857,10 @@ func (v *View) getExistingImports() *collections.MultiMap[ModuleID, existingImpo node := ast.TryGetImportFromModuleSpecifier(moduleSpecifier) if node == nil { panic("error: did not expect node kind " + moduleSpecifier.Kind.String()) - } else if ast.IsVariableDeclarationInitializedToRequire(node.Parent) { + } else if ast.IsVariableDeclarationInitializedToRequire(node.Parent()) { if moduleSymbol := v.checker.ResolveExternalModuleName(moduleSpecifier, nil /*importAttributesType*/); moduleSymbol != nil { if moduleID, _, ok := tryGetModuleIDAndFileNameOfModuleSymbol(moduleSymbol); ok { - result.Add(moduleID, existingImport{node: node.Parent, moduleSpecifier: moduleSpecifier.Text(), index: i}) + result.Add(moduleID, existingImport{node: node.Parent(), moduleSpecifier: moduleSpecifier.Text(), index: i}) } } } else if node.Kind == ast.KindImportDeclaration || node.Kind == ast.KindImportEqualsDeclaration || node.Kind == ast.KindJSDocImportTag { @@ -932,7 +932,7 @@ func detectSyntaxIndicators(file *ast.SourceFile, options *core.CompilerOptions) if imp.Flags&ast.NodeFlagsSynthesized != 0 { continue } - parent := imp.Parent + parent := imp.Parent() if parent == nil { continue } @@ -1123,14 +1123,14 @@ func promoteFromTypeOnly( case ast.KindImportSpecifier: spec := aliasDeclaration.AsImportSpecifier() if spec.IsTypeOnly { - if spec.Parent != nil && spec.Parent.Kind == ast.KindNamedImports { - namedImportsNode := spec.Parent.AsNamedImports() - elements := namedImportsNode.Elements.Nodes + if spec.Parent() != nil && spec.Parent().Kind == ast.KindNamedImports { + namedImportsNode := spec.Parent().AsNamedImports() + elements := namedImportsNode.Elements().Nodes if len(elements) > 1 { // Create a synthetic specifier with isTypeOnly=false to compute sorted position var propertyName *ast.Node - if spec.PropertyName != nil { - propertyName = changes.NodeFactory.NewIdentifier(spec.PropertyName.Text()).AsIdentifier().AsNode() + if spec.PropertyName() != nil { + propertyName = changes.NodeFactory.NewIdentifier(spec.PropertyName().Text()).AsIdentifier().AsNode() } newSpecifier := changes.NodeFactory.NewImportSpecifier( false, // isTypeOnly = false @@ -1138,7 +1138,7 @@ func promoteFromTypeOnly( changes.NodeFactory.NewIdentifier(spec.Name().Text()), ) specifierComparer, _ := lsutil.GetNamedImportSpecifierComparerWithDetection( - spec.Parent.Parent.Parent, // ImportDeclaration + spec.Parent().Parent().Parent(), // ImportDeclaration sourceFile, preferences, ) @@ -1146,7 +1146,7 @@ func promoteFromTypeOnly( currentIndex := slices.Index(elements, aliasDeclaration) if insertionIndex != currentIndex { changes.Delete(sourceFile, aliasDeclaration) - changes.InsertImportSpecifierAtIndex(sourceFile, newSpecifier, spec.Parent, insertionIndex) + changes.InsertImportSpecifierAtIndex(sourceFile, newSpecifier, spec.Parent(), insertionIndex) return aliasDeclaration } } @@ -1154,8 +1154,8 @@ func promoteFromTypeOnly( firstToken := lsutil.GetFirstToken(aliasDeclaration, sourceFile) typeKeywordPos := scanner.GetTokenPosOfNode(firstToken, sourceFile, false) var targetNode *ast.DeclarationName - if spec.PropertyName != nil { - targetNode = spec.PropertyName + if spec.PropertyName() != nil { + targetNode = spec.PropertyName() } else { targetNode = spec.Name() } @@ -1165,14 +1165,14 @@ func promoteFromTypeOnly( return aliasDeclaration } else { // The parent import clause is type-only - if spec.Parent == nil || spec.Parent.Kind != ast.KindNamedImports { + if spec.Parent() == nil || spec.Parent().Kind != ast.KindNamedImports { panic("ImportSpecifier parent must be NamedImports") } - if spec.Parent.Parent == nil || spec.Parent.Parent.Kind != ast.KindImportClause { + if spec.Parent().Parent() == nil || spec.Parent().Parent().Kind != ast.KindImportClause { panic("NamedImports parent must be ImportClause") } - promoteImportClause(changes, spec.Parent.Parent.AsImportClause(), compilerOptions, sourceFile, preferences, convertExistingToTypeOnly, aliasDeclaration) - return spec.Parent.Parent + promoteImportClause(changes, spec.Parent().Parent().AsImportClause(), compilerOptions, sourceFile, preferences, convertExistingToTypeOnly, aliasDeclaration) + return spec.Parent().Parent() } case ast.KindImportClause: @@ -1181,11 +1181,11 @@ func promoteFromTypeOnly( case ast.KindNamespaceImport: // Promote the parent import clause - if aliasDeclaration.Parent == nil || aliasDeclaration.Parent.Kind != ast.KindImportClause { + if aliasDeclaration.Parent() == nil || aliasDeclaration.Parent().Kind != ast.KindImportClause { panic("NamespaceImport parent must be ImportClause") } - promoteImportClause(changes, aliasDeclaration.Parent.AsImportClause(), compilerOptions, sourceFile, preferences, convertExistingToTypeOnly, aliasDeclaration) - return aliasDeclaration.Parent + promoteImportClause(changes, aliasDeclaration.Parent().AsImportClause(), compilerOptions, sourceFile, preferences, convertExistingToTypeOnly, aliasDeclaration) + return aliasDeclaration.Parent() case ast.KindImportEqualsDeclaration: // Remove the 'type' keyword (which is the second token: 'import' 'type' name '=' ...) @@ -1218,7 +1218,7 @@ func promoteImportClause( // Handle .ts extension conversion to .js if necessary if compilerOptions.AllowImportingTsExtensions.IsFalse() { - moduleSpecifier := checker.TryGetModuleSpecifierFromDeclaration(importClause.Parent) + moduleSpecifier := checker.TryGetModuleSpecifierFromDeclaration(importClause.Parent()) if moduleSpecifier != nil { // Note: We can't check ResolvedUsingTsExtension without program, so we'll skip this optimization // The fix will still work, just might not change .ts to .js extensions in all cases @@ -1229,13 +1229,13 @@ func promoteImportClause( // If convertExistingToTypeOnly is true, we need to add 'type' to other specifiers // in the same import declaration if convertExistingToTypeOnly.IsTrue() { - namedImports := importClause.NamedBindings + namedImports := importClause.NamedBindings() if namedImports != nil && namedImports.Kind == ast.KindNamedImports { namedImportsData := namedImports.AsNamedImports() - if len(namedImportsData.Elements.Nodes) > 1 { + if len(namedImportsData.Elements().Nodes) > 1 { // Check if the list is sorted and if we need to reorder _, isSorted := lsutil.GetNamedImportSpecifierComparerWithDetection( - importClause.Parent, + importClause.Parent(), sourceFile, preferences, ) @@ -1247,7 +1247,7 @@ func promoteImportClause( aliasDeclaration.Kind == ast.KindImportSpecifier { // Find the index of the alias declaration aliasIndex := -1 - for i, element := range namedImportsData.Elements.Nodes { + for i, element := range namedImportsData.Elements().Nodes { if element == aliasDeclaration { aliasIndex = i break @@ -1263,7 +1263,7 @@ func promoteImportClause( } // Add 'type' keyword to all other import specifiers that aren't already type-only - for _, element := range namedImportsData.Elements.Nodes { + for _, element := range namedImportsData.Elements().Nodes { spec := element.AsImportSpecifier() // Skip the specifier being promoted (if aliasDeclaration is an ImportSpecifier) if aliasDeclaration != nil && aliasDeclaration.Kind == ast.KindImportSpecifier { @@ -1301,8 +1301,8 @@ func deleteTypeKeyword(changes *change.Tracker, sourceFile *ast.SourceFile, star func getModuleSpecifierText(promotedDeclaration *ast.Node) string { if promotedDeclaration.Kind == ast.KindImportEqualsDeclaration { importEqualsDeclaration := promotedDeclaration.AsImportEqualsDeclaration() - if ast.IsExternalModuleReference(importEqualsDeclaration.ModuleReference) { - expr := importEqualsDeclaration.ModuleReference.Expression() + if ast.IsExternalModuleReference(importEqualsDeclaration.ModuleReference()) { + expr := importEqualsDeclaration.ModuleReference().Expression() if expr != nil { if ast.IsStringLiteralLike(expr) { return expr.Text() @@ -1310,9 +1310,9 @@ func getModuleSpecifierText(promotedDeclaration *ast.Node) string { return scanner.GetTextOfNode(expr) } } - return scanner.GetTextOfNode(importEqualsDeclaration.ModuleReference) + return scanner.GetTextOfNode(importEqualsDeclaration.ModuleReference()) } - moduleSpecifier := promotedDeclaration.Parent.ModuleSpecifier() + moduleSpecifier := promotedDeclaration.Parent().ModuleSpecifier() if ast.IsStringLiteralLike(moduleSpecifier) { return moduleSpecifier.Text() } diff --git a/tsc/internal/ls/autoimport/import_adder.go b/tsc/internal/ls/autoimport/import_adder.go index ca2fd62d80ecd..c0997a2f0a234 100644 --- a/tsc/internal/ls/autoimport/import_adder.go +++ b/tsc/internal/ls/autoimport/import_adder.go @@ -429,10 +429,10 @@ func TryGetAutoImportableReferenceFromTypeNode(importTypeNode *ast.TypeNode, idT var visitor *ast.NodeVisitor factory := ast.NewNodeFactory(ast.NodeFactoryHooks{}) visit := func(node *ast.Node) *ast.Node { - if ast.IsLiteralImportTypeNode(node) && node.AsImportTypeNode().Qualifier != nil { + if ast.IsLiteralImportTypeNode(node) && node.AsImportTypeNode().Qualifier() != nil { importTypeNode := node.AsImportTypeNode() // Symbol for the left-most thing after the dot - firstIdentifier := ast.GetFirstIdentifier(importTypeNode.Qualifier) + firstIdentifier := ast.GetFirstIdentifier(importTypeNode.Qualifier()) symbol := idToSymbol[firstIdentifier] if symbol == nil { // if symbol is missing then this doesn't come from a synthesized import type node @@ -443,12 +443,12 @@ func TryGetAutoImportableReferenceFromTypeNode(importTypeNode *ast.TypeNode, idT name := getNameForExportedSymbol(symbol, false /*preferCapitalized*/) var qualifier *ast.EntityName if name != firstIdentifier.Text() { - qualifier = replaceFirstIdentifierOfEntityName(factory, importTypeNode.Qualifier, factory.NewIdentifier(name)) + qualifier = replaceFirstIdentifierOfEntityName(factory, importTypeNode.Qualifier(), factory.NewIdentifier(name)) } else { - qualifier = importTypeNode.Qualifier + qualifier = importTypeNode.Qualifier() } symbols = append(symbols, symbol) - typeArguments := visitor.VisitNodes(importTypeNode.TypeArguments) + typeArguments := visitor.VisitNodes(importTypeNode.TypeArguments()) return factory.NewTypeReferenceNode(qualifier, typeArguments) } return visitor.VisitEachChild(node) @@ -483,8 +483,8 @@ func replaceFirstIdentifierOfEntityName(factory *ast.NodeFactory, name *ast.Enti return newIdentifier } return factory.NewQualifiedName( - replaceFirstIdentifierOfEntityName(factory, name.AsQualifiedName().Left, newIdentifier), - name.AsQualifiedName().Right, + replaceFirstIdentifierOfEntityName(factory, name.AsQualifiedName().Left(), newIdentifier), + name.AsQualifiedName().Right(), ) } diff --git a/tsc/internal/ls/autoinsert.go b/tsc/internal/ls/autoinsert.go index e7c36d04ca492..1a6ff9e2a79a5 100644 --- a/tsc/internal/ls/autoinsert.go +++ b/tsc/internal/ls/autoinsert.go @@ -33,22 +33,22 @@ func (l *LanguageService) ProvideOnAutoInsert(ctx context.Context, params *lspro var closingText string var element *ast.Node - if token.Kind == ast.KindGreaterThanToken && ast.IsJsxOpeningElement(token.Parent) { - element = token.Parent.Parent - } else if ast.IsJsxText(token) && ast.IsJsxElement(token.Parent) { - element = token.Parent + if token.Kind == ast.KindGreaterThanToken && ast.IsJsxOpeningElement(token.Parent()) { + element = token.Parent().Parent() + } else if ast.IsJsxText(token) && ast.IsJsxElement(token.Parent()) { + element = token.Parent() } if element != nil && isUnclosedTag(element.AsJsxElement()) { - tagNameNode := element.AsJsxElement().OpeningElement.TagName() + tagNameNode := element.AsJsxElement().OpeningElement().TagName() // Slight divergence from Strada - we don't use the verbatim text from the opening tag. closingText = "" } else { var fragment *ast.Node - if token.Kind == ast.KindGreaterThanToken && ast.IsJsxOpeningFragment(token.Parent) { - fragment = token.Parent.Parent - } else if ast.IsJsxText(token) && ast.IsJsxFragment(token.Parent) { - fragment = token.Parent + if token.Kind == ast.KindGreaterThanToken && ast.IsJsxOpeningFragment(token.Parent()) { + fragment = token.Parent().Parent() + } else if ast.IsJsxText(token) && ast.IsJsxFragment(token.Parent()) { + fragment = token.Parent() } if fragment != nil && isUnclosedFragment(fragment.AsJsxFragment()) { @@ -75,28 +75,28 @@ func (l *LanguageService) ProvideOnAutoInsert(ctx context.Context, params *lspro } func isUnclosedTag(node *ast.JsxElement) bool { - openingElement := node.OpeningElement - closingElement := node.ClosingElement + openingElement := node.OpeningElement() + closingElement := node.ClosingElement() if !ast.TagNamesAreEquivalent(openingElement.TagName(), closingElement.TagName()) { return true } - parent := node.Parent + parent := node.Parent() if ast.IsJsxElement(parent) { parent := parent.AsJsxElement() - return ast.TagNamesAreEquivalent(openingElement.TagName(), parent.OpeningElement.TagName()) && isUnclosedTag(parent) + return ast.TagNamesAreEquivalent(openingElement.TagName(), parent.OpeningElement().TagName()) && isUnclosedTag(parent) } return false } func isUnclosedFragment(node *ast.JsxFragment) bool { - closingFragment := node.ClosingFragment + closingFragment := node.ClosingFragment() if closingFragment.Flags&ast.NodeFlagsThisNodeHasError != 0 { return true } - parent := node.Parent + parent := node.Parent() if ast.IsJsxFragment(parent) && isUnclosedFragment(parent.AsJsxFragment()) { return true } diff --git a/tsc/internal/ls/callhierarchy.go b/tsc/internal/ls/callhierarchy.go index f04de1e0bf85d..641c756a98621 100644 --- a/tsc/internal/ls/callhierarchy.go +++ b/tsc/internal/ls/callhierarchy.go @@ -54,7 +54,7 @@ func isAssignedExpression(node *ast.Node) bool { if node.Name() != nil { return false } - parent := node.Parent + parent := node.Parent() if !isVariableLike(parent) { return false } @@ -133,7 +133,7 @@ func getCallHierarchyDeclarationReferenceNode(node *ast.Node) *ast.Node { } if isAssignedExpression(node) { - return node.Parent.Name() + return node.Parent().Name() } if modifiers := node.Modifiers(); modifiers != nil { @@ -184,7 +184,7 @@ func getCallHierarchyItemName(program *compiler.Program, node *ast.Node) (text s end := pos + 6 // "static".length c, done := program.GetTypeCheckerForFile(context.Background(), sourceFile) defer done() - symbol := c.GetSymbolAtLocation(node.Parent) + symbol := c.GetSymbolAtLocation(node.Parent()) prefix := "" if symbol != nil { prefix = c.SymbolToString(symbol) + " " @@ -194,7 +194,7 @@ func getCallHierarchyItemName(program *compiler.Program, node *ast.Node) (text s var declName *ast.Node if isAssignedExpression(node) { - declName = node.Parent.Name() + declName = node.Parent().Name() } else { declName = ast.GetNameOfDeclaration(node) } @@ -251,20 +251,20 @@ func getTextOfCallHierarchyName(program *compiler.Program, sourceNode *ast.Node, func getCallHierarchyItemContainerName(program *compiler.Program, node *ast.Node) string { if isAssignedExpression(node) { - parent := node.Parent - if ast.IsPropertyDeclaration(parent) && ast.IsClassLike(parent.Parent) { - if ast.IsClassExpression(parent.Parent) { - if assignedName := ast.GetAssignedName(parent.Parent); assignedName != nil { + parent := node.Parent() + if ast.IsPropertyDeclaration(parent) && ast.IsClassLike(parent.Parent()) { + if ast.IsClassExpression(parent.Parent()) { + if assignedName := ast.GetAssignedName(parent.Parent()); assignedName != nil { return getTextOfCallHierarchyName(program, node, assignedName, assignedName) } } else { - if name := parent.Parent.Name(); name != nil { + if name := parent.Parent().Name(); name != nil { return getTextOfCallHierarchyName(program, node, name, name) } } } - if parent.Parent.Parent != nil && parent.Parent.Parent.Parent != nil && ast.IsModuleBlock(parent.Parent.Parent.Parent) { - modParent := parent.Parent.Parent.Parent.Parent + if parent.Parent().Parent() != nil && parent.Parent().Parent().Parent() != nil && ast.IsModuleBlock(parent.Parent().Parent().Parent()) { + modParent := parent.Parent().Parent().Parent().Parent() if ast.IsModuleDeclaration(modParent) { if name := modParent.Name(); name != nil && ast.IsIdentifier(name) { return name.Text() @@ -276,18 +276,18 @@ func getCallHierarchyItemContainerName(program *compiler.Program, node *ast.Node switch node.Kind { case ast.KindGetAccessor, ast.KindSetAccessor, ast.KindMethodDeclaration: - if node.Parent.Kind == ast.KindObjectLiteralExpression { - if assignedName := ast.GetAssignedName(node.Parent); assignedName != nil { + if node.Parent().Kind == ast.KindObjectLiteralExpression { + if assignedName := ast.GetAssignedName(node.Parent()); assignedName != nil { return getTextOfCallHierarchyName(program, node, assignedName, assignedName) } } - if name := ast.GetNameOfDeclaration(node.Parent); name != nil { + if name := ast.GetNameOfDeclaration(node.Parent()); name != nil { return getTextOfCallHierarchyName(program, node, name, name) } case ast.KindFunctionDeclaration, ast.KindClassDeclaration, ast.KindModuleDeclaration: - if ast.IsModuleBlock(node.Parent) { - if ast.IsModuleDeclaration(node.Parent.Parent) { - if name := node.Parent.Parent.Name(); name != nil && ast.IsIdentifier(name) { + if ast.IsModuleBlock(node.Parent()) { + if ast.IsModuleDeclaration(node.Parent().Parent()) { + if name := node.Parent().Parent().Name(); name != nil && ast.IsIdentifier(name) { return name.Text() } } @@ -320,7 +320,7 @@ func findImplementation(c *checker.Checker, node *ast.Node) *ast.Node { } if ast.IsConstructorDeclaration(node) { - return ast.GetFirstConstructorWithBody(node.Parent) + return ast.GetFirstConstructorWithBody(node.Parent()) } if ast.IsFunctionDeclaration(node) || ast.IsMethodDeclaration(node) { @@ -376,7 +376,7 @@ func findAllInitialDeclarations(c *checker.Checker, node *ast.Node) []*ast.Node for _, i := range indices { decl := symbol.Declarations[i] if isValidCallHierarchyDeclaration(decl) { - if lastDecl == nil || lastDecl.Parent != decl.Parent || lastDecl.End() != decl.Pos() { + if lastDecl == nil || lastDecl.Parent() != decl.Parent() || lastDecl.End() != decl.Pos() { declarations = append(declarations, decl) } lastDecl = decl @@ -442,17 +442,17 @@ func resolveCallHierarchyDeclaration(program *compiler.Program, location *ast.No } if ast.IsDeclarationName(location) { - if isValidCallHierarchyDeclaration(location.Parent) { - return findImplementationOrAllInitialDeclarations(c, location.Parent) + if isValidCallHierarchyDeclaration(location.Parent()) { + return findImplementationOrAllInitialDeclarations(c, location.Parent()) } - if isPossibleCallHierarchyDeclaration(location.Parent) { - ancestor := ast.FindAncestor(location.Parent, isValidCallHierarchyDeclaration) + if isPossibleCallHierarchyDeclaration(location.Parent()) { + ancestor := ast.FindAncestor(location.Parent(), isValidCallHierarchyDeclaration) if ancestor != nil { return findImplementationOrAllInitialDeclarations(c, ancestor) } } - if isVariableLike(location.Parent) { - initializer := location.Parent.Initializer() + if isVariableLike(location.Parent()) { + initializer := location.Parent().Initializer() if initializer != nil && isAssignedExpression(initializer) { return initializer } @@ -461,14 +461,14 @@ func resolveCallHierarchyDeclaration(program *compiler.Program, location *ast.No } if ast.IsConstructorDeclaration(location) { - if isValidCallHierarchyDeclaration(location.Parent) { - return location.Parent + if isValidCallHierarchyDeclaration(location.Parent()) { + return location.Parent() } return nil } - if location.Kind == ast.KindStaticKeyword && ast.IsClassStaticBlockDeclaration(location.Parent) { - location = location.Parent + if location.Kind == ast.KindStaticKeyword && ast.IsClassStaticBlockDeclaration(location.Parent()) { + location = location.Parent() continue } @@ -720,7 +720,7 @@ func (c *callSiteCollector) recordCallSite(node *ast.Node) { switch { case ast.IsTaggedTemplateExpression(node): - target = node.AsTaggedTemplateExpression().Tag + target = node.AsTaggedTemplateExpression().Tag() case ast.IsJsxOpeningElement(node): target = node.TagName() case ast.IsJsxSelfClosingElement(node): @@ -831,8 +831,8 @@ func (c *callSiteCollector) collect(node *ast.Node) { // do not descend into the type arguments of a tagged template expression c.recordCallSite(node) taggedTemplate := node.AsTaggedTemplateExpression() - c.collect(taggedTemplate.Tag) - c.collect(taggedTemplate.Template) + c.collect(taggedTemplate.Tag()) + c.collect(taggedTemplate.Template()) return case ast.KindJsxOpeningElement, ast.KindJsxSelfClosingElement: // do not descend into the type arguments of a JsxOpeningLikeElement @@ -932,7 +932,7 @@ func collectCallSites(program *compiler.Program, c *checker.Checker, node *ast.N case ast.KindClassStaticBlockDeclaration: staticBlock := node.AsClassStaticBlockDeclaration() - collector.collect(staticBlock.Body) + collector.collect(staticBlock.Body()) default: debug.AssertNever(node) diff --git a/tsc/internal/ls/change/delete.go b/tsc/internal/ls/change/delete.go index 8156e36e4d0be..8c0bdee67cc45 100644 --- a/tsc/internal/ls/change/delete.go +++ b/tsc/internal/ls/change/delete.go @@ -17,9 +17,9 @@ import ( func deleteDeclaration(t *Tracker, deletedNodesInLists map[*ast.Node]bool, sourceFile *ast.SourceFile, node *ast.Node) { switch node.Kind { case ast.KindParameter: - oldFunction := node.Parent + oldFunction := node.Parent() if oldFunction.Kind == ast.KindArrowFunction && - len(oldFunction.AsArrowFunction().Parameters.Nodes) == 1 && + len(oldFunction.AsArrowFunction().Parameters().Nodes) == 1 && astnav.FindChildOfKind(oldFunction, ast.KindOpenParenToken, sourceFile) == nil { // Lambdas with exactly one parameter are special because, after removal, there // must be an empty parameter list (i.e. `()`) and this won't necessarily be the @@ -31,7 +31,7 @@ func deleteDeclaration(t *Tracker, deletedNodesInLists map[*ast.Node]bool, sourc case ast.KindImportDeclaration, ast.KindImportEqualsDeclaration: imports := sourceFile.Imports() - isFirstImport := len(imports) > 0 && node == imports[0].Parent || + isFirstImport := len(imports) > 0 && node == imports[0].Parent() || node == core.Find(sourceFile.Statements.Nodes, func(s *ast.Node) bool { return ast.IsAnyImportSyntax(s) }) // For first import, leave header comment in place, otherwise only delete JSDoc comments leadingTrivia := LeadingTriviaOptionStartLine @@ -43,9 +43,9 @@ func deleteDeclaration(t *Tracker, deletedNodesInLists map[*ast.Node]bool, sourc deleteNode(t, sourceFile, node, leadingTrivia, TrailingTriviaOptionInclude) case ast.KindBindingElement: - pattern := node.Parent + pattern := node.Parent() preserveComma := pattern.Kind == ast.KindArrayBindingPattern && - node != pattern.AsBindingPattern().Elements.Nodes[len(pattern.AsBindingPattern().Elements.Nodes)-1] + node != pattern.AsBindingPattern().Elements().Nodes[len(pattern.AsBindingPattern().Elements().Nodes)-1] if preserveComma { deleteNode(t, sourceFile, node, LeadingTriviaOptionIncludeAll, TrailingTriviaOptionExclude) } else { @@ -59,8 +59,8 @@ func deleteDeclaration(t *Tracker, deletedNodesInLists map[*ast.Node]bool, sourc deleteNodeInList(t, deletedNodesInLists, sourceFile, node) case ast.KindImportSpecifier: - namedImports := node.Parent - if len(namedImports.AsNamedImports().Elements.Nodes) == 1 { + namedImports := node.Parent() + if len(namedImports.AsNamedImports().Elements().Nodes) == 1 { deleteImportBinding(t, sourceFile, namedImports) } else { deleteNodeInList(t, deletedNodesInLists, sourceFile, node) @@ -88,12 +88,12 @@ func deleteDeclaration(t *Tracker, deletedNodesInLists map[*ast.Node]bool, sourc deleteNode(t, sourceFile, node, leadingTrivia, TrailingTriviaOptionInclude) default: - if node.Parent == nil { + if node.Parent() == nil { // a misbehaving client can reach here with the SourceFile node deleteNode(t, sourceFile, node, LeadingTriviaOptionIncludeAll, TrailingTriviaOptionInclude) - } else if node.Parent.Kind == ast.KindImportClause && node.Parent.AsImportClause().Name() == node { - deleteDefaultImport(t, sourceFile, node.Parent) - } else if node.Parent.Kind == ast.KindCallExpression && slices.Contains(node.Parent.AsCallExpression().Arguments.Nodes, node) { + } else if node.Parent().Kind == ast.KindImportClause && node.Parent().AsImportClause().Name() == node { + deleteDefaultImport(t, sourceFile, node.Parent()) + } else if node.Parent().Kind == ast.KindCallExpression && slices.Contains(node.Parent().AsCallExpression().Arguments().Nodes, node) { deleteNodeInList(t, deletedNodesInLists, sourceFile, node) } else { deleteNode(t, sourceFile, node, LeadingTriviaOptionIncludeAll, TrailingTriviaOptionInclude) @@ -103,9 +103,9 @@ func deleteDeclaration(t *Tracker, deletedNodesInLists map[*ast.Node]bool, sourc func deleteDefaultImport(t *Tracker, sourceFile *ast.SourceFile, importClause *ast.Node) { clause := importClause.AsImportClause() - if clause.NamedBindings == nil { + if clause.NamedBindings() == nil { // Delete the whole import - deleteNode(t, sourceFile, importClause.Parent, LeadingTriviaOptionIncludeAll, TrailingTriviaOptionInclude) + deleteNode(t, sourceFile, importClause.Parent(), LeadingTriviaOptionIncludeAll, TrailingTriviaOptionInclude) } else { // import |d,| * as ns from './file' name := clause.Name() @@ -122,7 +122,7 @@ func deleteDefaultImport(t *Tracker, sourceFile *ast.SourceFile, importClause *a } func deleteImportBinding(t *Tracker, sourceFile *ast.SourceFile, node *ast.Node) { - importClause := node.Parent.AsImportClause() + importClause := node.Parent().AsImportClause() if importClause.Name() != nil { // Delete named imports while preserving the default import // import d|, * as ns| from './file' @@ -142,7 +142,7 @@ func deleteImportBinding(t *Tracker, sourceFile *ast.SourceFile, node *ast.Node) } func deleteVariableDeclaration(t *Tracker, deletedNodesInLists map[*ast.Node]bool, sourceFile *ast.SourceFile, node *ast.Node) { - parent := node.Parent + parent := node.Parent() if parent.Kind == ast.KindCatchClause { // TODO: There's currently no unused diagnostic for this, could be a suggestion @@ -153,12 +153,12 @@ func deleteVariableDeclaration(t *Tracker, deletedNodesInLists map[*ast.Node]boo return } - if len(parent.AsVariableDeclarationList().Declarations.Nodes) != 1 { + if len(parent.AsVariableDeclarationList().Declarations().Nodes) != 1 { deleteNodeInList(t, deletedNodesInLists, sourceFile, node) return } - gp := parent.Parent + gp := parent.Parent() switch gp.Kind { case ast.KindForOfStatement, ast.KindForInStatement: t.ReplaceNode(sourceFile, node, t.NodeFactory.NewObjectLiteralExpression(t.NodeFactory.NewNodeList([]*ast.Node{}), false), nil) diff --git a/tsc/internal/ls/change/tracker.go b/tsc/internal/ls/change/tracker.go index d797d2cc821f4..200ed1a56ffb7 100644 --- a/tsc/internal/ls/change/tracker.go +++ b/tsc/internal/ls/change/tracker.go @@ -281,13 +281,13 @@ func (t *Tracker) TryInsertTypeAnnotation(sourceFile *ast.SourceFile, node *ast. } else { switch node.Kind { case ast.KindVariableDeclaration: - endNode = node.AsVariableDeclaration().ExclamationToken + endNode = node.AsVariableDeclaration().ExclamationToken() case ast.KindPropertySignature: - endNode = node.AsPropertySignatureDeclaration().PostfixToken + endNode = node.AsPropertySignatureDeclaration().PostfixToken() case ast.KindPropertyDeclaration: - endNode = node.AsPropertyDeclaration().PostfixToken + endNode = node.AsPropertyDeclaration().PostfixToken() case ast.KindParameter: - endNode = node.AsParameterDeclaration().QuestionToken + endNode = node.AsParameterDeclaration().QuestionToken() } if endNode == nil { endNode = node.Name() @@ -322,7 +322,7 @@ func (t *Tracker) InsertModifierBefore(sourceFile *ast.SourceFile, modifier ast. pos := astnav.GetStartOfNode(before, sourceFile, false) token := t.NewToken(modifier) token.Loc = core.NewTextRange(pos, pos) - token.Parent = before.Parent + token.SetParent(before.Parent()) t.InsertNodeAt(sourceFile, core.TextPos(pos), token, NodeOptions{Suffix: " "}) } @@ -402,7 +402,7 @@ func (t *Tracker) endPosForInsertNodeAfter(sourceFile *ast.SourceFile, after *as endPos := core.TextPos(after.End()) semicolon := t.NewToken(ast.KindSemicolonToken) semicolon.Loc = core.NewTextRange(after.End(), after.End()) - semicolon.Parent = after.Parent + semicolon.SetParent(after.Parent()) t.ReplaceRange( sourceFile, core.NewTextRange(int(endPos), int(endPos)), @@ -491,7 +491,7 @@ func (t *Tracker) InsertNodeInListAfter(sourceFile *ast.SourceFile, after *ast.N separatorToken := t.NewToken(separator) separatorString := scanner.TokenToString(separator) separatorToken.Loc = core.NewTextRange(end, end+len(separatorString)) - separatorToken.Parent = after.Parent + separatorToken.SetParent(after.Parent()) endPos := core.TextPos(end) t.ReplaceRange(sourceFile, core.NewTextRange(int(endPos), int(endPos)), separatorToken, NodeOptions{}) // use the same indentation as 'after' item @@ -522,7 +522,7 @@ func (t *Tracker) InsertNodeInListAfter(sourceFile *ast.SourceFile, after *ast.N // InsertImportSpecifierAtIndex inserts a new import specifier at the specified index in a NamedImports list func (t *Tracker) InsertImportSpecifierAtIndex(sourceFile *ast.SourceFile, newSpecifier *ast.Node, namedImports *ast.Node, index int) { namedImportsNode := namedImports.AsNamedImports() - elements := namedImportsNode.Elements.Nodes + elements := namedImportsNode.Elements().Nodes var prevSpecifier *ast.Node if index > 0 && index-1 < len(elements) { @@ -535,7 +535,7 @@ func (t *Tracker) InsertImportSpecifierAtIndex(sourceFile *ast.SourceFile, newSp sourceFile, elements[0], newSpecifier, - !positionsAreOnSameLine(astnav.GetStartOfNode(elements[0], sourceFile, false), astnav.GetStartOfNode(namedImports.Parent.Parent, sourceFile, false), sourceFile), + !positionsAreOnSameLine(astnav.GetStartOfNode(elements[0], sourceFile, false), astnav.GetStartOfNode(namedImports.Parent().Parent(), sourceFile, false), sourceFile), LeadingTriviaOptionNone, ) } @@ -706,7 +706,7 @@ func (t *Tracker) getOptionsForInsertNodeBefore(before *ast.Node, inserted *ast. return NodeOptions{Suffix: ", "} } return NodeOptions{} - } else if (before.Kind == ast.KindStringLiteral && before.Parent != nil && before.Parent.Kind == ast.KindImportDeclaration) || before.Kind == ast.KindNamedImports { + } else if (before.Kind == ast.KindStringLiteral && before.Parent() != nil && before.Parent().Kind == ast.KindImportDeclaration) || before.Kind == ast.KindNamedImports { return NodeOptions{Suffix: ", "} } else if before.Kind == ast.KindImportSpecifier { suffix := "," @@ -798,7 +798,7 @@ func rangeContainsRangeExclusive(outer *ast.Node, inner *ast.Node) bool { } func isSeparator(node *ast.Node, candidate *ast.Node) bool { - return candidate != nil && node.Parent != nil && (candidate.Kind == ast.KindCommaToken || (candidate.Kind == ast.KindSemicolonToken && node.Parent.Kind == ast.KindObjectLiteralExpression)) + return candidate != nil && node.Parent() != nil && (candidate.Kind == ast.KindCommaToken || (candidate.Kind == ast.KindSemicolonToken && node.Parent().Kind == ast.KindObjectLiteralExpression)) } func findIndentationColumn(text string, lineStart, memberStart, tabSize int) int { diff --git a/tsc/internal/ls/codeactions_fixmissingtypeannotation.go b/tsc/internal/ls/codeactions_fixmissingtypeannotation.go index 7f25f281c5609..15db9f6595198 100644 --- a/tsc/internal/ls/codeactions_fixmissingtypeannotation.go +++ b/tsc/internal/ls/codeactions_fixmissingtypeannotation.go @@ -329,7 +329,7 @@ func (f *isolatedDeclarationsFixer) addInlineAssertion(span core.TextRange) stri } targetNode := findBestFittingNode(nodeWithDiag, span) - if targetNode == nil || isValueSignatureDeclaration(targetNode) || isValueSignatureDeclaration(targetNode.Parent) { + if targetNode == nil || isValueSignatureDeclaration(targetNode) || isValueSignatureDeclaration(targetNode.Parent()) { return "" } @@ -406,7 +406,7 @@ func (f *isolatedDeclarationsFixer) addInlineAssertion(span core.TextRange) stri func (f *isolatedDeclarationsFixer) extractAsVariable(span core.TextRange) string { nodeWithDiag := astnav.GetTokenAtPosition(f.sourceFile, span.Pos()) targetNode := findBestFittingNode(nodeWithDiag, span) - if targetNode == nil || isValueSignatureDeclaration(targetNode) || isValueSignatureDeclaration(targetNode.Parent) { + if targetNode == nil || isValueSignatureDeclaration(targetNode) || isValueSignatureDeclaration(targetNode.Parent()) { return "" } @@ -427,7 +427,7 @@ func (f *isolatedDeclarationsFixer) extractAsVariable(span core.TextRange) strin parentPropertyAssignment := ast.FindAncestorKind(targetNode, ast.KindPropertyAssignment) if parentPropertyAssignment != nil { // Identifiers or entity names can already be typeof-ed - if parentPropertyAssignment == targetNode.Parent && ast.IsEntityNameExpression(targetNode) { + if parentPropertyAssignment == targetNode.Parent() && ast.IsEntityNameExpression(targetNode) { return "" } @@ -438,9 +438,9 @@ func (f *isolatedDeclarationsFixer) extractAsVariable(span core.TextRange) strin // Handle spread elements: walk up to the spread's parent and handle const assertions if ast.IsSpreadElement(replacementTarget) { - replacementTarget = ast.WalkUpParenthesizedExpressions(replacementTarget.Parent) - if isConstAssertion(replacementTarget.Parent) { - replacementTarget = replacementTarget.Parent + replacementTarget = ast.WalkUpParenthesizedExpressions(replacementTarget.Parent()) + if isConstAssertion(replacementTarget.Parent()) { + replacementTarget = replacementTarget.Parent() initializationNode = replacementTarget } else { constRef := factory.NewTypeReferenceNode(factory.NewIdentifier("const"), nil) @@ -500,7 +500,7 @@ func findExpandoFunction(ch *checker.Checker, node *ast.Node) *ast.Node { assignmentTarget := expandoDeclaration // Some late bound expando members use the whole expression as the declaration. if ast.IsBinaryExpression(assignmentTarget) { - assignmentTarget = assignmentTarget.AsBinaryExpression().Left + assignmentTarget = assignmentTarget.AsBinaryExpression().Left() if !isExpandoPropertyDeclarationForFix(assignmentTarget) { return nil } @@ -508,9 +508,9 @@ func findExpandoFunction(ch *checker.Checker, node *ast.Node) *ast.Node { var expression *ast.Node if ast.IsPropertyAccessExpression(assignmentTarget) { - expression = assignmentTarget.AsPropertyAccessExpression().Expression + expression = assignmentTarget.AsPropertyAccessExpression().Expression() } else if ast.IsElementAccessExpression(assignmentTarget) { - expression = assignmentTarget.AsElementAccessExpression().Expression + expression = assignmentTarget.AsElementAccessExpression().Expression() } else { return nil } @@ -523,7 +523,7 @@ func findExpandoFunction(ch *checker.Checker, node *ast.Node) *ast.Node { properties := ch.GetPropertiesOfType(targetType) found := false for _, p := range properties { - if p.ValueDeclaration == expandoDeclaration || p.ValueDeclaration == expandoDeclaration.Parent { + if p.ValueDeclaration == expandoDeclaration || p.ValueDeclaration == expandoDeclaration.Parent() { found = true break } @@ -538,8 +538,8 @@ func findExpandoFunction(ch *checker.Checker, node *ast.Node) *ast.Node { } fn := symbol.ValueDeclaration - if (ast.IsFunctionExpression(fn) || ast.IsArrowFunction(fn)) && ast.IsVariableDeclaration(fn.Parent) { - return fn.Parent + if (ast.IsFunctionExpression(fn) || ast.IsArrowFunction(fn)) && ast.IsVariableDeclaration(fn.Parent()) { + return fn.Parent() } if ast.IsFunctionDeclaration(fn) { return fn @@ -590,7 +590,7 @@ func (f *isolatedDeclarationsFixer) transformExportAssignment(defaultExport *ast return "" } - expression := exportAssignment.Expression + expression := exportAssignment.Expression() typeNode := f.inferType(expression, nil) if typeNode == nil { return "" @@ -616,8 +616,8 @@ func (f *isolatedDeclarationsFixer) transformExportAssignment(defaultExport *ast func (f *isolatedDeclarationsFixer) transformExtendsClauseWithExpression(classDecl *ast.Node) string { cd := classDecl.AsClassDeclaration() var extendsClause *ast.Node - if cd.HeritageClauses != nil { - for _, clause := range cd.HeritageClauses.Nodes { + if cd.HeritageClauses() != nil { + for _, clause := range cd.HeritageClauses().Nodes { if clause.AsHeritageClause().Token == ast.KindExtendsKeyword { extendsClause = clause break @@ -628,12 +628,12 @@ func (f *isolatedDeclarationsFixer) transformExtendsClauseWithExpression(classDe return "" } - heritageTypes := extendsClause.AsHeritageClause().Types + heritageTypes := extendsClause.AsHeritageClause().Types() if heritageTypes == nil || len(heritageTypes.Nodes) == 0 { return "" } heritageExpression := heritageTypes.Nodes[0] - expression := heritageExpression.AsExpressionWithTypeArguments().Expression + expression := heritageExpression.AsExpressionWithTypeArguments().Expression() heritageTypeNode := f.inferType(expression, nil) if heritageTypeNode == nil { @@ -663,11 +663,11 @@ func (f *isolatedDeclarationsFixer) transformExtendsClauseWithExpression(classDe } func (f *isolatedDeclarationsFixer) transformDestructuringPatterns(bindingPattern *ast.Node) string { - enclosingVariableDeclaration := bindingPattern.Parent + enclosingVariableDeclaration := bindingPattern.Parent() if !ast.IsVariableDeclaration(enclosingVariableDeclaration) { return "" } - enclosingVarStmt := enclosingVariableDeclaration.Parent.Parent + enclosingVarStmt := enclosingVariableDeclaration.Parent().Parent() if !ast.IsVariableStatement(enclosingVarStmt) { return "" } @@ -703,10 +703,10 @@ func (f *isolatedDeclarationsFixer) transformDestructuringPatterns(bindingPatter } // If the enclosing variable statement has multiple declarations, preserve the non-destructuring ones - declList := enclosingVarStmt.AsVariableStatement().DeclarationList.AsVariableDeclarationList() - if len(declList.Declarations.Nodes) > 1 { + declList := enclosingVarStmt.AsVariableStatement().DeclarationList().AsVariableDeclarationList() + if len(declList.Declarations().Nodes) > 1 { var remainingDecls []*ast.Node - for _, d := range declList.Declarations.Nodes { + for _, d := range declList.Declarations().Nodes { if d != enclosingVariableDeclaration { remainingDecls = append(remainingDecls, d) } @@ -737,7 +737,7 @@ func (f *isolatedDeclarationsFixer) extractBindingElements( factory := f.changeTracker.NodeFactory if ast.IsObjectBindingPattern(bindingPattern) { - for _, element := range bindingPattern.AsBindingPattern().Elements.Nodes { + for _, element := range bindingPattern.AsBindingPattern().Elements().Nodes { if ast.IsOmittedExpression(element) { continue } @@ -749,18 +749,18 @@ func (f *isolatedDeclarationsFixer) extractBindingElements( // Build property access expression var accessExpr *ast.Node - if be.PropertyName != nil && ast.IsComputedPropertyName(be.PropertyName) { + if be.PropertyName() != nil && ast.IsComputedPropertyName(be.PropertyName()) { // Handle computed property names: create a temp variable for the computed expression - computedExpression := be.PropertyName.AsComputedPropertyName().Expression + computedExpression := be.PropertyName().AsComputedPropertyName().Expression() identifierForComputedProperty := f.changeTracker.EmitContext.Factory.NewGeneratedNameForNode(computedExpression) compVarDecl := factory.NewVariableDeclaration(identifierForComputedProperty.AsNode(), nil, nil, computedExpression) compVarDeclList := factory.NewVariableDeclarationList(factory.NewNodeList([]*ast.Node{compVarDecl}), ast.NodeFlagsConst) compVarStmt := factory.NewVariableStatement(nil, compVarDeclList) *newNodes = append(*newNodes, compVarStmt) accessExpr = factory.NewElementAccessExpression(baseExpr, nil, identifierForComputedProperty.AsNode(), ast.NodeFlagsNone) - } else if be.PropertyName != nil { + } else if be.PropertyName() != nil { // Use property name text (handles identifiers, string literals, numeric literals) - propText := be.PropertyName.Text() + propText := be.PropertyName().Text() accessExpr = factory.NewPropertyAccessExpression(baseExpr, nil, factory.NewIdentifier(propText), ast.NodeFlagsNone) } else if ast.IsIdentifier(name) { accessExpr = factory.NewPropertyAccessExpression(baseExpr, nil, factory.NewIdentifier(name.Text()), ast.NodeFlagsNone) @@ -775,7 +775,7 @@ func (f *isolatedDeclarationsFixer) extractBindingElements( } } } else if ast.IsArrayBindingPattern(bindingPattern) { - for i, element := range bindingPattern.AsBindingPattern().Elements.Nodes { + for i, element := range bindingPattern.AsBindingPattern().Elements().Nodes { if ast.IsOmittedExpression(element) { continue } @@ -809,10 +809,10 @@ func (f *isolatedDeclarationsFixer) emitBindingElementVariable( typeNode := f.inferType(name, nil) variableInitializer := accessExpr - if be.Initializer != nil { + if be.Initializer() != nil { // Create a temp variable to hold the accessed value, then use a conditional expression // to apply the default: temp === undefined ? defaultValue : temp - propName := be.PropertyName + propName := be.PropertyName() tempBaseName := "temp" if propName != nil && ast.IsIdentifier(propName) { tempBaseName = propName.Text() @@ -832,7 +832,7 @@ func (f *isolatedDeclarationsFixer) emitBindingElementVariable( factory.NewIdentifier("undefined"), ), factory.NewToken(ast.KindQuestionToken), - be.Initializer, + be.Initializer(), factory.NewToken(ast.KindColonToken), variableInitializer, ) @@ -955,7 +955,7 @@ func (f *isolatedDeclarationsFixer) typeFromArraySpreadElements(node *ast.ArrayL name, isInConstContext, func(n *ast.Node) []*ast.Node { - return n.AsArrayLiteralExpression().Elements.Nodes + return n.AsArrayLiteralExpression().Elements().Nodes }, ast.IsSpreadElement, func(expr *ast.Node) *ast.Node { @@ -987,8 +987,8 @@ func (f *isolatedDeclarationsFixer) typeFromObjectSpreadAssignment(node *ast.Obj name, isInConstContext, func(n *ast.Node) []*ast.Node { - if n.AsObjectLiteralExpression().Properties != nil { - return n.AsObjectLiteralExpression().Properties.Nodes + if n.AsObjectLiteralExpression().Properties() != nil { + return n.AsObjectLiteralExpression().Properties().Nodes } return nil }, @@ -1151,12 +1151,12 @@ func (f *isolatedDeclarationsFixer) relativeType(node *ast.Node) *ast.TypeNode { } if ast.IsConditionalExpression(node) { cond := node.AsConditionalExpression() - trueType := f.relativeType(cond.WhenTrue) + trueType := f.relativeType(cond.WhenTrue()) if trueType == nil { return nil } trueMutated := f.mutatedTarget - falseType := f.relativeType(cond.WhenFalse) + falseType := f.relativeType(cond.WhenFalse()) if falseType == nil { return nil } @@ -1188,7 +1188,7 @@ func (f *isolatedDeclarationsFixer) typeToMinimizedReferenceType(t *checker.Type trimmedArgs := f.changeTracker.NodeFactory.NewNodeList(nodeTypeArgs[:cutoff]) typeNode = f.changeTracker.NodeFactory.UpdateTypeReferenceNode( typeNode.AsTypeReferenceNode(), - typeNode.AsTypeReferenceNode().TypeName, + typeNode.AsTypeReferenceNode().TypeName(), trimmedArgs, ) } @@ -1250,7 +1250,7 @@ func typeParamHasDefault(tp *checker.Type) bool { return false } for _, decl := range sym.Declarations { - if ast.IsTypeParameterDeclaration(decl) && decl.AsTypeParameterDeclaration().DefaultType != nil { + if ast.IsTypeParameterDeclaration(decl) && decl.AsTypeParameterDeclaration().DefaultType() != nil { return true } } @@ -1269,8 +1269,8 @@ func (f *isolatedDeclarationsFixer) addTypeToVariableLike(decl *ast.Node) string // Parenthesize paren-less arrow function parameters (`x => ...`) so the inserted `: T` // produces `(x: T) => ...` instead of the invalid `x: T => ...`. Queued after the type // annotation so that the `)` edit at param.End() sorts after the annotation insertion. - if ast.IsParameterDeclaration(decl) && decl.Parent != nil && ast.IsArrowFunction(decl.Parent) { - f.changeTracker.ParenthesizeArrowParameters(f.sourceFile, decl.Parent) + if ast.IsParameterDeclaration(decl) && decl.Parent() != nil && ast.IsArrowFunction(decl.Parent()) { + f.changeTracker.ParenthesizeArrowParameters(f.sourceFile, decl.Parent()) } } return diagnostics.Add_annotation_of_type_0.Localize(f.locale, typeToStringForDiag(typeNode, f.sourceFile, f.changeTracker)) @@ -1309,7 +1309,7 @@ func findAncestorWithMissingType(node *ast.Node) *ast.Node { return false } if ast.IsObjectBindingPattern(n) || ast.IsArrayBindingPattern(n) { - return ast.IsVariableDeclaration(n.Parent) + return ast.IsVariableDeclaration(n.Parent()) } return true }) @@ -1321,16 +1321,16 @@ func findBestFittingNode(node *ast.Node, span core.TextRange) *ast.Node { return nil } for node != nil && node.End() < span.Pos()+span.Len() { - node = node.Parent + node = node.Parent() } - for node.Parent != nil && node.Parent.Pos() == node.Pos() && node.Parent.End() == node.End() { - node = node.Parent + for node.Parent() != nil && node.Parent().Pos() == node.Pos() && node.Parent().End() == node.End() { + node = node.Parent() } - if ast.IsIdentifier(node) && ast.HasInitializer(node.Parent) && node.Parent.Initializer() != nil { - return node.Parent.Initializer() + if ast.IsIdentifier(node) && ast.HasInitializer(node.Parent()) && node.Parent().Initializer() != nil { + return node.Parent().Initializer() } - if ast.IsIdentifier(node) && ast.IsShorthandPropertyAssignment(node.Parent) { - return node.Parent + if ast.IsIdentifier(node) && ast.IsShorthandPropertyAssignment(node.Parent()) { + return node.Parent() } return node } @@ -1393,27 +1393,27 @@ func (f *isolatedDeclarationsFixer) addSymbolToExistingImport(sym *ast.Symbol) { continue } importDecl := stmt.AsImportDeclaration() - if importDecl.ImportClause == nil { + if importDecl.ImportClause() == nil { continue } // Check if this import is from the same module - importModuleSymbol := f.checker.GetSymbolAtLocation(importDecl.ModuleSpecifier) + importModuleSymbol := f.checker.GetSymbolAtLocation(importDecl.ModuleSpecifier()) if importModuleSymbol == nil || f.checker.GetMergedSymbol(importModuleSymbol) != f.checker.GetMergedSymbol(moduleSymbol) { continue } // Found the matching import - add the symbol to named imports - importClause := importDecl.ImportClause.AsImportClause() - if importClause.NamedBindings != nil && ast.IsNamedImports(importClause.NamedBindings) { + importClause := importDecl.ImportClause().AsImportClause() + if importClause.NamedBindings() != nil && ast.IsNamedImports(importClause.NamedBindings()) { // Add to existing named imports - existingElements := importClause.NamedBindings.AsNamedImports().Elements.Nodes + existingElements := importClause.NamedBindings().AsNamedImports().Elements().Nodes factory := f.changeTracker.NodeFactory newSpecifier := factory.NewImportSpecifier(false, nil, factory.NewIdentifier(symbolName)) newElements := append(existingElements, newSpecifier.AsNode()) newNamedImports := factory.NewNamedImports(factory.NewNodeList(newElements)) newImportClause := factory.UpdateImportClause(importClause, importClause.PhaseModifier, importClause.Name(), newNamedImports) - newImportDecl := factory.UpdateImportDeclaration(importDecl, importDecl.Modifiers(), newImportClause, importDecl.ModuleSpecifier, importDecl.Attributes) + newImportDecl := factory.UpdateImportDeclaration(importDecl, importDecl.Modifiers(), newImportClause, importDecl.ModuleSpecifier(), importDecl.Attributes()) f.changeTracker.ReplaceNode(f.sourceFile, stmt, newImportDecl.AsNode(), nil) } return diff --git a/tsc/internal/ls/codeactions_importfixes.go b/tsc/internal/ls/codeactions_importfixes.go index 49bc0f51c3f76..87da7159c68cd 100644 --- a/tsc/internal/ls/codeactions_importfixes.go +++ b/tsc/internal/ls/codeactions_importfixes.go @@ -275,7 +275,7 @@ func getUmdSymbol(token *ast.Node, ch *checker.Checker) *ast.Symbol { } // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. - parent := token.Parent + parent := token.Parent() if (ast.IsJsxOpeningLikeElement(parent) && parent.TagName() == token) || ast.IsJsxOpeningFragment(parent) { var location *ast.Node @@ -377,7 +377,7 @@ type symbolNameInfo struct { } func getSymbolNamesToImport(sourceFile *ast.SourceFile, ch *checker.Checker, symbolToken *ast.Node, compilerOptions *core.CompilerOptions) []symbolNameInfo { - parent := symbolToken.Parent + parent := symbolToken.Parent() if (ast.IsJsxOpeningLikeElement(parent) || ast.IsJsxClosingElement(parent)) && parent.TagName() == symbolToken && jsxModeNeedsExplicitImport(compilerOptions.Jsx) { diff --git a/tsc/internal/ls/codeactions_missingmemberfixer.go b/tsc/internal/ls/codeactions_missingmemberfixer.go index 8368acd005bed..32d6c1b074936 100644 --- a/tsc/internal/ls/codeactions_missingmemberfixer.go +++ b/tsc/internal/ls/codeactions_missingmemberfixer.go @@ -233,18 +233,18 @@ func (f *missingMemberFixer) createSignatureDeclarationFromSignature(signature * if ast.IsTypeParameterDeclaration(tp) { typeParameter := tp.AsTypeParameterDeclaration() - constraint := typeParameter.Constraint + constraint := typeParameter.Constraint() if constraint != nil { constraint = f.importTypeNode(constraint, idToSymbol) } - defaultType := typeParameter.DefaultType + defaultType := typeParameter.DefaultType() if defaultType != nil { defaultType = f.importTypeNode(defaultType, idToSymbol) } nodes = append(nodes, - f.changeTracker.NodeFactory.UpdateTypeParameterDeclaration(typeParameter, typeParameter.Modifiers(), typeParameter.Name(), constraint, typeParameter.Expression, defaultType)) + f.changeTracker.NodeFactory.UpdateTypeParameterDeclaration(typeParameter, typeParameter.Modifiers(), typeParameter.Name(), constraint, typeParameter.Expression(), defaultType)) } else { nodes = append(nodes, tp) } @@ -260,13 +260,13 @@ func (f *missingMemberFixer) createSignatureDeclarationFromSignature(signature * } parameter := p.AsParameterDeclaration() - parameterTypeNode := parameter.Type + parameterTypeNode := parameter.Type() if parameterTypeNode != nil { parameterTypeNode = f.importTypeNode(parameterTypeNode, idToSymbol) } nodes = append(nodes, - f.changeTracker.NodeFactory.UpdateParameterDeclaration(parameter, parameter.Modifiers(), parameter.DotDotDotToken, parameter.Name(), core.IfElse(isJS, nil, parameter.QuestionToken), parameterTypeNode, parameter.Initializer)) + f.changeTracker.NodeFactory.UpdateParameterDeclaration(parameter, parameter.Modifiers(), parameter.DotDotDotToken(), parameter.Name(), core.IfElse(isJS, nil, parameter.QuestionToken()), parameterTypeNode, parameter.Initializer())) } parameters = f.changeTracker.NodeFactory.NewNodeList(nodes) } @@ -283,20 +283,20 @@ func (f *missingMemberFixer) createSignatureDeclarationFromSignature(signature * switch kind { case ast.KindFunctionExpression: fn := signatureDeclaration.AsFunctionExpression() - return f.changeTracker.NodeFactory.UpdateFunctionExpression(fn, modifiers, fn.AsteriskToken, core.IfElse(name != nil && ast.IsIdentifier(name), name, nil), typeParameters, parameters, typeNode, fn.FullSignature, core.OrElse(body, fn.Body)) + return f.changeTracker.NodeFactory.UpdateFunctionExpression(fn, modifiers, fn.AsteriskToken(), core.IfElse(name != nil && ast.IsIdentifier(name), name, nil), typeParameters, parameters, typeNode, fn.FullSignature(), core.OrElse(body, fn.Body())) case ast.KindArrowFunction: fn := signatureDeclaration.AsArrowFunction() - return f.changeTracker.NodeFactory.UpdateArrowFunction(fn, modifiers, typeParameters, parameters, typeNode, fn.FullSignature, fn.EqualsGreaterThanToken, core.OrElse(body, fn.Body)) + return f.changeTracker.NodeFactory.UpdateArrowFunction(fn, modifiers, typeParameters, parameters, typeNode, fn.FullSignature(), fn.EqualsGreaterThanToken(), core.OrElse(body, fn.Body())) case ast.KindMethodDeclaration: method := signatureDeclaration.AsMethodDeclaration() methodName := core.IfElse(name == nil, f.changeTracker.NodeFactory.NewIdentifier(""), createPropertyName(f.changeTracker.NodeFactory, name, quotePreference)) - return f.changeTracker.NodeFactory.UpdateMethodDeclaration(method, modifiers, method.AsteriskToken, methodName, questionToken, typeParameters, parameters, typeNode, method.FullSignature, body) + return f.changeTracker.NodeFactory.UpdateMethodDeclaration(method, modifiers, method.AsteriskToken(), methodName, questionToken, typeParameters, parameters, typeNode, method.FullSignature(), body) case ast.KindFunctionDeclaration: fn := signatureDeclaration.AsFunctionDeclaration() - return f.changeTracker.NodeFactory.UpdateFunctionDeclaration(fn, modifiers, fn.AsteriskToken, core.IfElse(name != nil && ast.IsIdentifier(name), name, nil), typeParameters, parameters, typeNode, fn.FullSignature, core.OrElse(body, fn.Body)) + return f.changeTracker.NodeFactory.UpdateFunctionDeclaration(fn, modifiers, fn.AsteriskToken(), core.IfElse(name != nil && ast.IsIdentifier(name), name, nil), typeParameters, parameters, typeNode, fn.FullSignature(), core.OrElse(body, fn.Body())) } return nil @@ -340,11 +340,11 @@ func (f *missingMemberFixer) createSignatureDeclarationFromSignatures(signatures questionToken = f.changeTracker.NodeFactory.NewToken(ast.KindQuestionToken) } - parameters.Nodes = append(parameters.Nodes, f.changeTracker.NodeFactory.NewParameterDeclaration( + parameters.SetNodes(append(parameters.Nodes, f.changeTracker.NodeFactory.NewParameterDeclaration( nil /*modifiers*/, f.changeTracker.NodeFactory.NewToken(ast.KindDotDotDotToken), f.changeTracker.NodeFactory.NewIdentifier(restParameterName), questionToken, f.changeTracker.NodeFactory.NewArrayTypeNode(f.changeTracker.NodeFactory.NewKeywordTypeNode(ast.KindUnknownKeyword)), nil, /*initializer*/ - )) + ))) } methodName := core.IfElse(name == nil, f.changeTracker.NodeFactory.NewIdentifier(""), createPropertyName(f.changeTracker.NodeFactory, name, quotePreference)) diff --git a/tsc/internal/ls/codelens.go b/tsc/internal/ls/codelens.go index 357cd1513278a..a159f30f546bd 100644 --- a/tsc/internal/ls/codelens.go +++ b/tsc/internal/ls/codelens.go @@ -194,11 +194,11 @@ func isValidImplementationsCodeLensNode(node *ast.Node, userPrefs lsutil.CodeLen // If configured, show on interface methods case ast.KindMethodSignature: - return userPrefs.ImplementationsCodeLensShowOnInterfaceMethods.IsTrue() && node.Parent.Kind == ast.KindInterfaceDeclaration + return userPrefs.ImplementationsCodeLensShowOnInterfaceMethods.IsTrue() && node.Parent().Kind == ast.KindInterfaceDeclaration // If configured, show on all class methods - but not private ones. case ast.KindMethodDeclaration: - if userPrefs.ImplementationsCodeLensShowOnAllClassMethods.IsTrue() && node.Parent.Kind == ast.KindClassDeclaration { + if userPrefs.ImplementationsCodeLensShowOnAllClassMethods.IsTrue() && node.Parent().Kind == ast.KindClassDeclaration { return !ast.HasModifier(node, ast.ModifierFlagsPrivate) && node.Name().Kind != ast.KindPrivateIdentifier } fallthrough @@ -233,7 +233,7 @@ func isValidReferenceLensNode(node *ast.Node, userPrefs lsutil.CodeLensUserPrefe // For https://github.com/microsoft/vscode/issues/90396 // !!! - switch node.Parent.Kind { + switch node.Parent().Kind { case ast.KindClassDeclaration, ast.KindInterfaceDeclaration, ast.KindTypeLiteral: return true } diff --git a/tsc/internal/ls/completions.go b/tsc/internal/ls/completions.go index ff0f180d5b84d..52fcacbbdbedd 100644 --- a/tsc/internal/ls/completions.go +++ b/tsc/internal/ls/completions.go @@ -445,10 +445,10 @@ func (l *LanguageService) getCompletionsAtPosition( if previousToken != nil && (previousToken.Kind == ast.KindBreakKeyword || previousToken.Kind == ast.KindContinueKeyword || previousToken.Kind == ast.KindIdentifier) && - ast.IsBreakOrContinueStatement(previousToken.Parent) { + ast.IsBreakOrContinueStatement(previousToken.Parent()) { return l.getLabelCompletionsAtPosition( ctx, - previousToken.Parent, + previousToken.Parent(), file, position, l.getOptionalReplacementSpan(previousToken, file), @@ -592,8 +592,8 @@ func (l *LanguageService) getCompletionData( currentToken = astnav.GetTokenAtPosition(file, position) if currentToken == nil || (!ast.IsDeclarationName(currentToken) && - (currentToken.Parent.Kind != ast.KindJSDocPropertyTag || - currentToken.Parent.Name() != currentToken)) { + (currentToken.Parent().Kind != ast.KindJSDocPropertyTag || + currentToken.Parent().Name() != currentToken)) { // Use as type location if inside tag's type expression insideJSDocTagTypeExpression = isCurrentlyEditingNode(typeExpression, file, position) } @@ -669,7 +669,7 @@ func (l *LanguageService) getCompletionData( return nil, nil } - parent := contextToken.Parent + parent := contextToken.Parent() if contextToken.Kind == ast.KindDotToken || contextToken.Kind == ast.KindQuestionDotToken { isRightOfDot = contextToken.Kind == ast.KindDotToken isRightOfQuestionDot = contextToken.Kind == ast.KindQuestionDotToken @@ -689,7 +689,7 @@ func (l *LanguageService) getCompletionData( return nil, nil } case ast.KindQualifiedName: - node = parent.AsQualifiedName().Left + node = parent.AsQualifiedName().Left() case ast.KindModuleDeclaration: node = parent.Name() case ast.KindImportType: @@ -710,7 +710,7 @@ func (l *LanguageService) getCompletionData( // Then, try to get a JSX container and its associated attributes type. if parent != nil && parent.Kind == ast.KindPropertyAccessExpression { contextToken = parent - parent = parent.Parent + parent = parent.Parent() } // Fix location @@ -750,7 +750,7 @@ func (l *LanguageService) getCompletionData( // Second case is for `
`. // Second case must not match for `
`. if previousToken.Kind == ast.KindCloseBraceToken || - previousToken.Kind == ast.KindIdentifier && previousToken.Parent.Kind == ast.KindJsxAttribute { + previousToken.Kind == ast.KindIdentifier && previousToken.Parent().Kind == ast.KindJsxAttribute { isJsxIdentifierExpected = true } case ast.KindJsxAttribute: @@ -765,7 +765,7 @@ func (l *LanguageService) getCompletionData( isJsxIdentifierExpected = true // For `
` we don't want to treat this as a jsx inializer, instead it's the attribute name. - if parent != previousToken.Parent && + if parent != previousToken.Parent() && parent.Initializer() == nil && astnav.FindChildOfKind(parent, ast.KindEqualsToken, file) != nil { jsxInitializer.initializer = previousToken @@ -786,7 +786,7 @@ func (l *LanguageService) getCompletionData( symbolToSortTextMap := map[ast.SymbolId]SortText{} var seenPropertySymbols collections.Set[ast.SymbolId] isTypeOnlyLocation := insideJSDocTagTypeExpression || insideJsDocImportTag || - importStatementCompletion != nil && location.Parent != nil && ast.IsTypeOnlyImportOrExportDeclaration(location.Parent) || + importStatementCompletion != nil && location.Parent() != nil && ast.IsTypeOnlyImportOrExportDeclaration(location.Parent()) || !isContextTokenValueLocation(contextToken) && (isPossiblyTypeArgumentPosition(contextToken, file, typeChecker) || ast.IsPartOfTypeNode(location) || @@ -874,7 +874,7 @@ func (l *LanguageService) getCompletionData( if node.Kind == ast.KindImportType { propertyAccess = node } else { - propertyAccess = node.Parent + propertyAccess = node.Parent() } if inCheckedFile { @@ -915,11 +915,11 @@ func (l *LanguageService) getCompletionData( // Since this is qualified name check it's a type node location isImportType := ast.IsLiteralImportTypeNode(node) isTypeLocation := (isImportType && !node.AsImportTypeNode().IsTypeOf) || - ast.IsPartOfTypeNode(node.Parent) || + ast.IsPartOfTypeNode(node.Parent()) || isPossiblyTypeArgumentPosition(contextToken, file, typeChecker) isRhsOfImportDeclaration := isInRightSideOfInternalImportEqualsDeclaration(node) if ast.IsEntityName(node) || isImportType || ast.IsPropertyAccessExpression(node) { - isNamespaceName := ast.IsModuleDeclaration(node.Parent) + isNamespaceName := ast.IsModuleDeclaration(node.Parent()) if isNamespaceName { isNewIdentifierLocation = true defaultCommitCharacters = []string{} @@ -932,7 +932,7 @@ func (l *LanguageService) getCompletionData( if isImportType { valueAccessNode = node } else { - valueAccessNode = node.Parent + valueAccessNode = node.Parent() } // Extract module or enum members exportedSymbols := typeChecker.GetExportsOfModule(symbol) @@ -951,7 +951,7 @@ func (l *LanguageService) getCompletionData( // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion. isValidAccess = exportedSymbol.Flags&ast.SymbolFlagsNamespace != 0 && !core.Every(exportedSymbol.Declarations, func(declaration *ast.Declaration) bool { - return declaration.Parent == node.Parent + return declaration.Parent() == node.Parent() }) } else if isRhsOfImportDeclaration { // Any kind is allowed when dotting off namespace in internal import equals declaration @@ -1029,8 +1029,8 @@ func (l *LanguageService) getCompletionData( } intersectionTypeNode := core.IfElse( - ast.IsIntersectionTypeNode(typeLiteralNode.Parent), - typeLiteralNode.Parent, + ast.IsIntersectionTypeNode(typeLiteralNode.Parent()), + typeLiteralNode.Parent(), nil, ) containerTypeNode := core.IfElse( @@ -1112,7 +1112,7 @@ func (l *LanguageService) getCompletionData( } // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false - rootDeclaration := ast.GetRootDeclaration(objectLikeContainer.Parent) + rootDeclaration := ast.GetRootDeclaration(objectLikeContainer.Parent()) if !ast.IsVariableLike(rootDeclaration) { panic("Root declaration is not variable-like.") } @@ -1124,14 +1124,14 @@ func (l *LanguageService) getCompletionData( // type of parameter will flow in from the contextual type of the function. canGetType := ast.HasInitializer(rootDeclaration) || ast.GetTypeAnnotationNode(rootDeclaration) != nil || - rootDeclaration.Parent.Parent.Kind == ast.KindForOfStatement + rootDeclaration.Parent().Parent().Kind == ast.KindForOfStatement if !canGetType && rootDeclaration.Kind == ast.KindParameter { - if ast.IsExpression(rootDeclaration.Parent) { - canGetType = typeChecker.GetContextualType(rootDeclaration.Parent, checker.ContextFlagsNone) != nil - } else if rootDeclaration.Parent.Kind == ast.KindMethodDeclaration || - rootDeclaration.Parent.Kind == ast.KindSetAccessor { - canGetType = ast.IsExpression(rootDeclaration.Parent.Parent) && - typeChecker.GetContextualType(rootDeclaration.Parent.Parent, checker.ContextFlagsNone) != nil + if ast.IsExpression(rootDeclaration.Parent()) { + canGetType = typeChecker.GetContextualType(rootDeclaration.Parent(), checker.ContextFlagsNone) != nil + } else if rootDeclaration.Parent().Kind == ast.KindMethodDeclaration || + rootDeclaration.Parent().Kind == ast.KindSetAccessor { + canGetType = ast.IsExpression(rootDeclaration.Parent().Parent()) && + typeChecker.GetContextualType(rootDeclaration.Parent().Parent(), checker.ContextFlagsNone) != nil } } if canGetType { @@ -1283,11 +1283,11 @@ func (l *LanguageService) getCompletionData( // `import { |` or `import { a as 0, | }` or `import { type | }` var namedImportsOrExports *ast.NamedImportsOrExports if contextToken.Kind == ast.KindOpenBraceToken || contextToken.Kind == ast.KindCommaToken { - namedImportsOrExports = core.IfElse(isNamedImportsOrExports(contextToken.Parent), contextToken.Parent, nil) + namedImportsOrExports = core.IfElse(isNamedImportsOrExports(contextToken.Parent()), contextToken.Parent(), nil) } else if isTypeKeywordTokenOrIdentifier(contextToken) { namedImportsOrExports = core.IfElse( - isNamedImportsOrExports(contextToken.Parent.Parent), - contextToken.Parent.Parent, + isNamedImportsOrExports(contextToken.Parent().Parent()), + contextToken.Parent().Parent(), nil, ) } @@ -1304,8 +1304,8 @@ func (l *LanguageService) getCompletionData( // try to show exported member for imported/re-exported module moduleSpecifier := core.IfElse( namedImportsOrExports.Kind == ast.KindNamedImports, - namedImportsOrExports.Parent.Parent, - namedImportsOrExports.Parent, + namedImportsOrExports.Parent().Parent(), + namedImportsOrExports.Parent(), ).ModuleSpecifier() if moduleSpecifier == nil { isNewIdentifierLocation = true @@ -1353,17 +1353,17 @@ func (l *LanguageService) getCompletionData( var importAttributes *ast.Node switch contextToken.Kind { case ast.KindOpenBraceToken, ast.KindCommaToken: - importAttributes = contextToken.Parent + importAttributes = contextToken.Parent() case ast.KindColonToken: - importAttributes = contextToken.Parent.Parent + importAttributes = contextToken.Parent().Parent() } if importAttributes == nil || !ast.IsImportAttributes(importAttributes) { return globalsSearchContinue, nil } var elements []*ast.Node - if importAttributes.AsImportAttributes().Attributes != nil { - elements = importAttributes.AsImportAttributes().Attributes.Nodes + if importAttributes.AsImportAttributes().Attributes() != nil { + elements = importAttributes.AsImportAttributes().Attributes().Nodes } attributeNames := core.Map(elements, func(el *ast.Node) string { return el.AsImportAttribute().Name().Text() @@ -1390,7 +1390,7 @@ func (l *LanguageService) getCompletionData( } var namedExports *ast.NamedExportsNode if contextToken.Kind == ast.KindOpenBraceToken || contextToken.Kind == ast.KindCommaToken { - namedExports = core.IfElse(ast.IsNamedExports(contextToken.Parent), contextToken.Parent, nil) + namedExports = core.IfElse(ast.IsNamedExports(contextToken.Parent()), contextToken.Parent(), nil) } if namedExports == nil { @@ -1459,9 +1459,9 @@ func (l *LanguageService) getCompletionData( var classElement *ast.Node if contextToken.Kind == ast.KindSemicolonToken { - classElement = contextToken.Parent.Parent + classElement = contextToken.Parent().Parent() } else { - classElement = contextToken.Parent + classElement = contextToken.Parent() } var classElementModifierFlags ast.ModifierFlags if ast.IsClassElement(classElement) { @@ -1649,7 +1649,7 @@ func (l *LanguageService) getCompletionData( thisType := typeChecker.TryGetThisTypeAtEx( scopeNode, false, /*includeGlobalThis*/ - core.IfElse(ast.IsClassLike(scopeNode.Parent), scopeNode, nil), + core.IfElse(ast.IsClassLike(scopeNode.Parent()), scopeNode, nil), ) if thisType != nil && !isProbablyGlobalType(thisType, file, typeChecker) { for _, symbol := range getPropertiesForCompletion(thisType, typeChecker) { @@ -1665,7 +1665,7 @@ func (l *LanguageService) getCompletionData( return globalsSearchFail, err } if isTypeOnlyLocation { - if contextToken != nil && ast.IsAssertionExpression(contextToken.Parent) { + if contextToken != nil && ast.IsAssertionExpression(contextToken.Parent()) { keywordFilters = KeywordCompletionFiltersTypeAssertionKeywords } else { keywordFilters = KeywordCompletionFiltersTypeKeywords @@ -1713,7 +1713,7 @@ func (l *LanguageService) getCompletionData( completionKind = CompletionKindGlobal keywordFilters = KeywordCompletionFiltersNone } else if isStartingCloseTag { - tagName := contextToken.Parent.Parent.AsJsxElement().OpeningElement.TagName() + tagName := contextToken.Parent().Parent().AsJsxElement().OpeningElement().TagName() tagSymbol := typeChecker.GetSymbolAtLocation(tagName) if tagSymbol != nil { symbols = []*ast.Symbol{tagSymbol} @@ -1846,7 +1846,7 @@ func (l *LanguageService) completionInfoFromData( if caseClause != nil && (contextToken.Kind == ast.KindCaseKeyword || ast.IsNodeDescendantOf(contextToken, caseClause.Expression())) { - tracker := newCaseClauseTracker(typeChecker, caseClause.Parent.AsCaseBlock().Clauses.Nodes) + tracker := newCaseClauseTracker(typeChecker, caseClause.Parent().AsCaseBlock().Clauses().Nodes) literals = core.Filter(literals, func(literal literalValue) bool { return !tracker.hasValue(literal) }) @@ -2274,7 +2274,7 @@ func (l *LanguageService) createCompletionItem( } precedingToken := astnav.FindPrecedingToken(file, data.propertyAccessToConvert.Pos()) var awaitText string - if precedingToken != nil && lsutil.PositionIsASICandidate(precedingToken.End(), precedingToken.Parent, file) { + if precedingToken != nil && lsutil.PositionIsASICandidate(precedingToken.End(), precedingToken.Parent(), file) { awaitText = ";" } @@ -2285,10 +2285,10 @@ func (l *LanguageService) createCompletionItem( dotStr := core.IfElse(insertQuestionDot, "?.", ".") insertText = awaitText + dotStr + insertText } - isInAwaitExpression := ast.IsAwaitExpression(data.propertyAccessToConvert.Parent) + isInAwaitExpression := ast.IsAwaitExpression(data.propertyAccessToConvert.Parent()) wrapNode := core.IfElse( isInAwaitExpression, - data.propertyAccessToConvert.Parent, + data.propertyAccessToConvert.Parent(), data.propertyAccessToConvert.Expression(), ) lspRange, fidelity := l.createLspRangeFromBounds( @@ -2320,12 +2320,12 @@ func (l *LanguageService) createCompletionItem( if data.completionKind == CompletionKindObjectPropertyDeclaration && contextToken != nil && !ast.NodeHasKind(astnav.FindPrecedingTokenEx(file, contextToken.Pos(), contextToken, false /*excludeJSDoc*/), ast.KindCommaToken) { - if ast.IsMethodDeclaration(contextToken.Parent.Parent) || - ast.IsGetAccessorDeclaration(contextToken.Parent.Parent) || - ast.IsSetAccessorDeclaration(contextToken.Parent.Parent) || - ast.IsSpreadAssignment(contextToken.Parent) || - lsutil.GetLastToken(ast.FindAncestor(contextToken.Parent, ast.IsPropertyAssignment), file) == contextToken || - ast.IsShorthandPropertyAssignment(contextToken.Parent) && + if ast.IsMethodDeclaration(contextToken.Parent().Parent()) || + ast.IsGetAccessorDeclaration(contextToken.Parent().Parent()) || + ast.IsSetAccessorDeclaration(contextToken.Parent().Parent()) || + ast.IsSpreadAssignment(contextToken.Parent()) || + lsutil.GetLastToken(ast.FindAncestor(contextToken.Parent(), ast.IsPropertyAssignment), file) == contextToken || + ast.IsShorthandPropertyAssignment(contextToken.Parent()) && getLineOfPosition(file, contextToken.End()) != getLineOfPosition(file, position) { source = string(completionSourceObjectLiteralMemberWithComma) hasAction = true @@ -2367,7 +2367,7 @@ func (l *LanguageService) createCompletionItem( !data.isRightOfOpenTag && clientSupportsItemSnippet(ctx) && preferences.JsxAttributeCompletionStyle != lsutil.JsxAttributeCompletionStyleNone && - !(data.location.Parent != nil && ast.IsJsxAttribute(data.location.Parent) && data.location.Parent.Initializer() != nil) { + !(data.location.Parent() != nil && ast.IsJsxAttribute(data.location.Parent()) && data.location.Parent().Initializer() != nil) { useBraces := preferences.JsxAttributeCompletionStyle == lsutil.JsxAttributeCompletionStyleBraces t := typeChecker.GetTypeOfSymbolAtLocation(symbol, data.location) @@ -2539,15 +2539,15 @@ func (l *LanguageService) createObjectLiteralMethod(snippetPrinter *snippetPrint return nil } - parameters := make([]*ast.Node, 0, len(typeNode.AsFunctionTypeNode().Parameters.Nodes)) - for _, parameter := range typeNode.AsFunctionTypeNode().Parameters.Nodes { + parameters := make([]*ast.Node, 0, len(typeNode.AsFunctionTypeNode().Parameters().Nodes)) + for _, parameter := range typeNode.AsFunctionTypeNode().Parameters().Nodes { parameters = append(parameters, factory.NewParameterDeclaration( nil, /*modifiers*/ - parameter.AsParameterDeclaration().DotDotDotToken, + parameter.AsParameterDeclaration().DotDotDotToken(), parameter.Name().Clone(factory), nil, /*questionToken*/ nil, /*typeNode*/ - parameter.AsParameterDeclaration().Initializer, + parameter.AsParameterDeclaration().Initializer(), )) } @@ -2625,10 +2625,10 @@ func (l *LanguageService) printObjectLiteralMethodLabelDetail(method *ast.Node, methodSignature := factory.NewMethodSignatureDeclaration( nil, /*modifiers*/ factory.NewIdentifier(""), - methodDeclaration.PostfixToken, - methodDeclaration.TypeParameters, - methodDeclaration.Parameters, - methodDeclaration.Type, + methodDeclaration.PostfixToken(), + methodDeclaration.TypeParameters(), + methodDeclaration.Parameters(), + methodDeclaration.Type(), ) signaturePrinter := printer.NewPrinter(printer.PrinterOptions{ RemoveComments: true, @@ -2772,13 +2772,13 @@ func (l *LanguageService) getPresentMemberModifiers(contextToken *ast.Node, file rangePos := position rangeEnd := position - if ast.IsPropertyDeclaration(contextToken.Parent) { + if ast.IsPropertyDeclaration(contextToken.Parent()) { contextModifierKind := modifierLikeKind(contextToken) if contextModifierKind == ast.KindUnknown { return presentMemberModifiers{} } - modifierNodes := contextToken.Parent.ModifierNodes() + modifierNodes := contextToken.Parent().ModifierNodes() if len(modifierNodes) > 0 { modifiers |= ast.ModifiersToFlags(modifierNodes) & ast.ModifierFlagsModifier for _, modifier := range modifierNodes { @@ -2795,8 +2795,8 @@ func (l *LanguageService) getPresentMemberModifiers(contextToken *ast.Node, file rangePos = min(rangePos, astnav.GetStartOfNode(contextToken, file, false /*includeJSDoc*/)) } - if contextToken.Parent.Name() != contextToken { - rangeEnd = astnav.GetStartOfNode(contextToken.Parent.Name(), file, false /*includeJSDoc*/) + if contextToken.Parent().Name() != contextToken { + rangeEnd = astnav.GetStartOfNode(contextToken.Parent().Name(), file, false /*includeJSDoc*/) } } @@ -3052,8 +3052,8 @@ func isClassLikeMemberCompletion(symbol *ast.Symbol, location *ast.Node, file *a memberFlags := ast.SymbolFlagsClassMember & ast.SymbolFlagsEnumMemberExcludes return symbol.Flags&memberFlags != 0 && (ast.IsClassLike(location) || - (location.Parent != nil && location.Parent.Parent != nil && ast.IsClassElement(location.Parent) && location == location.Parent.Name() && lsutil.GetLastToken(location.Parent, file) == location.Parent.Name() && ast.IsClassLike(location.Parent.Parent)) || - (location.Parent != nil && ast.IsSyntaxList(location) && ast.IsClassLike(location.Parent))) + (location.Parent() != nil && location.Parent().Parent() != nil && ast.IsClassElement(location.Parent()) && location == location.Parent().Name() && lsutil.GetLastToken(location.Parent(), file) == location.Parent().Name() && ast.IsClassLike(location.Parent().Parent())) || + (location.Parent() != nil && ast.IsSyntaxList(location) && ast.IsClassLike(location.Parent()))) } func symbolAppearsToBeTypeOnly(symbol *ast.Symbol, typeChecker *checker.Checker) bool { @@ -3073,7 +3073,7 @@ func shouldIncludeSymbol( allFlags := symbol.Flags location := data.location // export = /**/ here we want to get all meanings, so any symbol is ok - if location.Parent != nil && ast.IsExportAssignment(location.Parent) { + if location.Parent() != nil && ast.IsExportAssignment(location.Parent()) { return true } @@ -3097,7 +3097,7 @@ func shouldIncludeSymbol( if closestSymbolDeclaration != nil && symbolDeclaration != nil { if ast.IsParameterDeclaration(closestSymbolDeclaration) && ast.IsParameterDeclaration(symbolDeclaration) { - parameters := closestSymbolDeclaration.Parent.ParameterList() + parameters := closestSymbolDeclaration.Parent().ParameterList() if symbolDeclaration.Pos() >= closestSymbolDeclaration.Pos() && symbolDeclaration.Pos() < parameters.End() { return false @@ -3109,8 +3109,8 @@ func shouldIncludeSymbol( // `type A = K` return false } - if isInTypeParameterDefault(data.contextToken) && !ast.IsInferTypeNode(closestSymbolDeclaration.Parent) { - typeParameters := closestSymbolDeclaration.Parent.TypeParameterList() + if isInTypeParameterDefault(data.contextToken) && !ast.IsInferTypeNode(closestSymbolDeclaration.Parent()) { + typeParameters := closestSymbolDeclaration.Parent().TypeParameterList() if typeParameters != nil && symbolDeclaration.Pos() >= closestSymbolDeclaration.Pos() && symbolDeclaration.Pos() < typeParameters.End() { return false @@ -3296,7 +3296,7 @@ func isValidTrigger(file *ast.SourceFile, triggerCharacter CompletionsTriggerCha // Opening JSX tag return contextToken != nil && contextToken.Kind == ast.KindLessThanToken && - (!ast.IsBinaryExpression(contextToken.Parent) || binaryExpressionMayBeOpenTag(contextToken.Parent.AsBinaryExpression())) + (!ast.IsBinaryExpression(contextToken.Parent()) || binaryExpressionMayBeOpenTag(contextToken.Parent().AsBinaryExpression())) case "/": if contextToken == nil { return false @@ -3304,9 +3304,9 @@ func isValidTrigger(file *ast.SourceFile, triggerCharacter CompletionsTriggerCha if ast.IsStringLiteralLike(contextToken) { return ast.TryGetImportFromModuleSpecifier(contextToken) != nil } - return contextToken.Kind == ast.KindLessThanSlashToken && ast.IsJsxClosingElement(contextToken.Parent) + return contextToken.Kind == ast.KindLessThanSlashToken && ast.IsJsxClosingElement(contextToken.Parent()) case " ": - return contextToken != nil && contextToken.Kind == ast.KindImportKeyword && contextToken.Parent.Kind == ast.KindSourceFile + return contextToken != nil && contextToken.Kind == ast.KindImportKeyword && contextToken.Parent().Kind == ast.KindSourceFile case "*": return isPotentiallyValidJSDocSnippetCompletionPosition(file, position) default: @@ -3324,7 +3324,7 @@ func isStringLiteralOrTemplate(node *ast.Node) bool { } func binaryExpressionMayBeOpenTag(binaryExpression *ast.BinaryExpression) bool { - return ast.NodeIsMissing(binaryExpression.Left) + return ast.NodeIsMissing(binaryExpression.Left()) } func isCheckedFile(file *ast.SourceFile, compilerOptions *core.CompilerOptions) bool { @@ -3333,8 +3333,8 @@ func isCheckedFile(file *ast.SourceFile, compilerOptions *core.CompilerOptions) func isContextTokenValueLocation(contextToken *ast.Node) bool { return contextToken != nil && ((contextToken.Kind == ast.KindTypeOfKeyword && - (contextToken.Parent.Kind == ast.KindTypeQuery || ast.IsTypeOfExpression(contextToken.Parent))) || - (contextToken.Kind == ast.KindAssertsKeyword && contextToken.Parent.Kind == ast.KindTypePredicate)) + (contextToken.Parent().Kind == ast.KindTypeQuery || ast.IsTypeOfExpression(contextToken.Parent()))) || + (contextToken.Kind == ast.KindAssertsKeyword && contextToken.Parent().Kind == ast.KindTypePredicate)) } func isPossiblyTypeArgumentPosition(token *ast.Node, sourceFile *ast.SourceFile, typeChecker *checker.Checker) bool { @@ -3346,7 +3346,7 @@ func isPossiblyTypeArgumentPosition(token *ast.Node, sourceFile *ast.SourceFile, func isContextTokenTypeLocation(contextToken *ast.Node) bool { if contextToken != nil { - parentKind := contextToken.Parent.Kind + parentKind := contextToken.Parent().Kind switch contextToken.Kind { case ast.KindColonToken: return parentKind == ast.KindPropertyDeclaration || @@ -3446,7 +3446,7 @@ func getNullableSymbolOriginInfoKind(kind symbolOriginInfoKind, insertQuestionDo func isStaticProperty(symbol *ast.Symbol) bool { return symbol.ValueDeclaration != nil && symbol.ValueDeclaration.ModifierFlags()&ast.ModifierFlagsStatic != 0 && - ast.IsClassLike(symbol.ValueDeclaration.Parent) + ast.IsClassLike(symbol.ValueDeclaration.Parent()) } // getContextualTypeForConditionalExpression handles completion within a conditional expression @@ -3465,7 +3465,7 @@ func getContextualTypeForConditionalExpression(conditionalExpr *ast.Node, positi } func getContextualType(previousToken *ast.Node, position int, file *ast.SourceFile, typeChecker *checker.Checker) *checker.Type { - parent := previousToken.Parent + parent := previousToken.Parent() switch previousToken.Kind { case ast.KindIdentifier: return getContextualTypeFromParent(previousToken, typeChecker, checker.ContextFlagsNone) @@ -3474,7 +3474,7 @@ func getContextualType(previousToken *ast.Node, position int, file *ast.SourceFi case ast.KindVariableDeclaration: return typeChecker.GetContextualType(parent.Initializer(), checker.ContextFlagsNone) case ast.KindBinaryExpression: - return typeChecker.GetTypeAtLocation(parent.AsBinaryExpression().Left) + return typeChecker.GetTypeAtLocation(parent.AsBinaryExpression().Left()) case ast.KindJsxAttribute: return typeChecker.GetContextualTypeForJsxAttribute(parent) default: @@ -3489,8 +3489,8 @@ func getContextualType(previousToken *ast.Node, position int, file *ast.SourceFi } return nil case ast.KindOpenBraceToken: - if ast.IsJsxExpression(parent) && !ast.IsJsxElement(parent.Parent) && !ast.IsJsxFragment(parent.Parent) { - return typeChecker.GetContextualTypeForJsxAttribute(parent.Parent) + if ast.IsJsxExpression(parent) && !ast.IsJsxElement(parent.Parent()) && !ast.IsJsxFragment(parent.Parent()) { + return typeChecker.GetContextualTypeForJsxAttribute(parent.Parent()) } return nil case ast.KindOpenBracketToken: @@ -3541,9 +3541,9 @@ func getContextualType(previousToken *ast.Node, position int, file *ast.SourceFi argInfo := getArgumentInfoForCompletions(previousToken, position, file, typeChecker) if argInfo != nil { return typeChecker.GetContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex) - } else if isEqualityOperatorKind(previousToken.Kind) && ast.IsBinaryExpression(parent) && isEqualityOperatorKind(parent.AsBinaryExpression().OperatorToken.Kind) { + } else if isEqualityOperatorKind(previousToken.Kind) && ast.IsBinaryExpression(parent) && isEqualityOperatorKind(parent.AsBinaryExpression().OperatorToken().Kind) { // completion at `x ===/**/` - return typeChecker.GetTypeAtLocation(parent.AsBinaryExpression().Left) + return typeChecker.GetTypeAtLocation(parent.AsBinaryExpression().Left()) } else { contextualType := typeChecker.GetContextualType(previousToken, checker.ContextFlagsIgnoreNodeInferences) if contextualType != nil { @@ -3554,7 +3554,7 @@ func getContextualType(previousToken *ast.Node, position int, file *ast.SourceFi } func getSwitchedType(caseClause *ast.CaseOrDefaultClauseNode, typeChecker *checker.Checker) *checker.Type { - return typeChecker.GetTypeAtLocation(caseClause.Parent.Parent.Expression()) + return typeChecker.GetTypeAtLocation(caseClause.Parent().Parent().Expression()) } func isEqualityOperatorKind(kind ast.Kind) bool { @@ -3619,7 +3619,7 @@ func getClosestSymbolDeclaration(contextToken *ast.Node, location *ast.Node) *as } if (ast.IsParameterDeclaration(node) || ast.IsTypeParameterDeclaration(node)) && - !ast.IsIndexSignatureDeclaration(node.Parent) { + !ast.IsIndexSignatureDeclaration(node.Parent()) { return ast.FindAncestorTrue } return ast.FindAncestorFalse @@ -3641,8 +3641,8 @@ func getClosestSymbolDeclaration(contextToken *ast.Node, location *ast.Node) *as } func isArrowFunctionBody(node *ast.Node) bool { - return node.Parent != nil && ast.IsArrowFunction(node.Parent) && - (node.Parent.Body() == node || + return node.Parent() != nil && ast.IsArrowFunction(node.Parent()) && + (node.Parent().Body() == node || // const a = () => /**/; node.Kind == ast.KindEqualsGreaterThanToken) } @@ -3653,13 +3653,13 @@ func isInTypeParameterDefault(contextToken *ast.Node) bool { } node := contextToken - parent := contextToken.Parent + parent := contextToken.Parent() for parent != nil { if ast.IsTypeParameterDeclaration(parent) { - return parent.AsTypeParameterDeclaration().DefaultType == node || node.Kind == ast.KindEqualsToken + return parent.AsTypeParameterDeclaration().DefaultType() == node || node.Kind == ast.KindEqualsToken } node = parent - parent = parent.Parent + parent = parent.Parent() } return false @@ -4008,7 +4008,7 @@ func getContextualKeywords(file *ast.SourceFile, contextToken *ast.Node, positio // export { foo } from "foo" | // Source: https://tc39.es/proposal-import-assertions/ if contextToken != nil { - parent := contextToken.Parent + parent := contextToken.Parent() tokenLine := scanner.GetECMALineOfPosition(file, contextToken.End()) currentLine := scanner.GetECMALineOfPosition(file, position) if (ast.IsImportDeclaration(parent) || @@ -4098,7 +4098,7 @@ func computeCommitCharactersAndIsNewIdentifier( if contextToken == nil { return false, allCommitCharacters } - containingNodeKind := contextToken.Parent.Kind + containingNodeKind := contextToken.Parent().Kind tokenKind := keywordForNode(contextToken) // Previous token may have been a keyword that was converted to an identifier. switch tokenKind { @@ -4107,7 +4107,7 @@ func computeCommitCharactersAndIsNewIdentifier( // func( a, | // new C(a, | case ast.KindCallExpression, ast.KindNewExpression: - expression := contextToken.Parent.Expression() + expression := contextToken.Parent().Expression() // func\n(a, | if getLineOfPosition(file, expression.End()) != getLineOfPosition(file, position) { return true, noCommaCommitCharacters @@ -4132,7 +4132,7 @@ func computeCommitCharactersAndIsNewIdentifier( // func( | // new C(a| case ast.KindCallExpression, ast.KindNewExpression: - expression := contextToken.Parent.Expression() + expression := contextToken.Parent().Expression() // func\n( | if getLineOfPosition(file, expression.End()) != getLineOfPosition(file, position) { return true, noCommaCommitCharacters @@ -4230,7 +4230,7 @@ func keywordForNode(node *ast.Node) ast.Kind { func getScopeNode(initialToken *ast.Node, position int, file *ast.SourceFile) *ast.Node { scope := initialToken for scope != nil && !positionBelongsToNode(scope, position, file) { - scope = scope.Parent + scope = scope.Parent() } return scope } @@ -4271,15 +4271,15 @@ func tryGetTypeLiteralNode(node *ast.Node) *ast.TypeLiteralNodeNode { return nil } - parent := node.Parent + parent := node.Parent() switch node.Kind { case ast.KindOpenBraceToken: if ast.IsTypeLiteralNode(parent) { return parent } case ast.KindSemicolonToken, ast.KindCommaToken, ast.KindIdentifier: - if parent.Kind == ast.KindPropertySignature && ast.IsTypeLiteralNode(parent.Parent) { - return parent.Parent + if parent.Kind == ast.KindPropertySignature && ast.IsTypeLiteralNode(parent.Parent()) { + return parent.Parent() } } @@ -4298,7 +4298,7 @@ func getConstraintOfTypeArgumentProperty(node *ast.Node, typeChecker *checker.Ch } } - t := getConstraintOfTypeArgumentProperty(node.Parent, typeChecker) + t := getConstraintOfTypeArgumentProperty(node.Parent(), typeChecker) if t == nil { return nil } @@ -4320,7 +4320,7 @@ func getConstraintOfTypeArgumentProperty(node *ast.Node, typeChecker *checker.Ch return nil case ast.KindColonToken: - if node.Parent.Kind == ast.KindPropertySignature { + if node.Parent().Kind == ast.KindPropertySignature { // The cursor is at a property value location like `Foo<{ x: | }`. // `t` already refers to the appropriate property type. return t @@ -4339,7 +4339,7 @@ func tryGetObjectLikeCompletionContainer(contextToken *ast.Node, position int, f return nil } - parent := contextToken.Parent + parent := contextToken.Parent() switch contextToken.Kind { // const x = { | // const x = { a: 0, | @@ -4348,44 +4348,44 @@ func tryGetObjectLikeCompletionContainer(contextToken *ast.Node, position int, f return parent } case ast.KindAsteriskToken: - if ast.IsMethodDeclaration(parent) && ast.IsObjectLiteralExpression(parent.Parent) { - return parent.Parent + if ast.IsMethodDeclaration(parent) && ast.IsObjectLiteralExpression(parent.Parent()) { + return parent.Parent() } case ast.KindAsyncKeyword: - if ast.IsObjectLiteralExpression(parent.Parent) { - return parent.Parent + if ast.IsObjectLiteralExpression(parent.Parent()) { + return parent.Parent() } case ast.KindIdentifier: if contextToken.Text() == "async" && ast.IsShorthandPropertyAssignment(parent) { - return parent.Parent + return parent.Parent() } else { - if ast.IsObjectLiteralExpression(parent.Parent) && + if ast.IsObjectLiteralExpression(parent.Parent()) && (ast.IsSpreadAssignment(parent) || ast.IsShorthandPropertyAssignment(parent) && getLineOfPosition(file, contextToken.End()) != getLineOfPosition(file, position)) { - return parent.Parent + return parent.Parent() } ancestorNode := ast.FindAncestor(parent, ast.IsPropertyAssignment) - if ancestorNode != nil && lsutil.GetLastToken(ancestorNode, file) == contextToken && ast.IsObjectLiteralExpression(ancestorNode.Parent) { - return ancestorNode.Parent + if ancestorNode != nil && lsutil.GetLastToken(ancestorNode, file) == contextToken && ast.IsObjectLiteralExpression(ancestorNode.Parent()) { + return ancestorNode.Parent() } } default: - if parent.Parent != nil && parent.Parent.Parent != nil && - (ast.IsMethodDeclaration(parent.Parent) || - ast.IsGetAccessorDeclaration(parent.Parent) || - ast.IsSetAccessorDeclaration(parent.Parent)) && - ast.IsObjectLiteralExpression(parent.Parent.Parent) { - return parent.Parent.Parent + if parent.Parent() != nil && parent.Parent().Parent() != nil && + (ast.IsMethodDeclaration(parent.Parent()) || + ast.IsGetAccessorDeclaration(parent.Parent()) || + ast.IsSetAccessorDeclaration(parent.Parent())) && + ast.IsObjectLiteralExpression(parent.Parent().Parent()) { + return parent.Parent().Parent() } - if ast.IsSpreadAssignment(parent) && ast.IsObjectLiteralExpression(parent.Parent) { - return parent.Parent + if ast.IsSpreadAssignment(parent) && ast.IsObjectLiteralExpression(parent.Parent()) { + return parent.Parent() } ancestorNode := ast.FindAncestor(parent, ast.IsPropertyAssignment) if contextToken.Kind != ast.KindColonToken && ancestorNode != nil && lsutil.GetLastToken(ancestorNode, file) == contextToken && - ast.IsObjectLiteralExpression(ancestorNode.Parent) { - return ancestorNode.Parent + ast.IsObjectLiteralExpression(ancestorNode.Parent()) { + return ancestorNode.Parent() } } @@ -4398,10 +4398,10 @@ func tryGetObjectLiteralContextualType(node *ast.ObjectLiteralExpressionNode, ty return t } - parent := ast.WalkUpParenthesizedExpressions(node.Parent) + parent := ast.WalkUpParenthesizedExpressions(node.Parent()) if ast.IsBinaryExpression(parent) && - parent.AsBinaryExpression().OperatorToken.Kind == ast.KindEqualsToken && - node == parent.AsBinaryExpression().Left { + parent.AsBinaryExpression().OperatorToken().Kind == ast.KindEqualsToken && + node == parent.AsBinaryExpression().Left() { // Object literal is assignment pattern: ({ | } = x) return typeChecker.GetTypeAtLocation(parent) } @@ -4446,7 +4446,7 @@ func getPropertiesForObjectExpression( if len(member.Declarations) == 0 { return true } - return core.Some(member.Declarations, func(decl *ast.Declaration) bool { return decl.Parent != obj }) + return core.Some(member.Declarations, func(decl *ast.Declaration) bool { return decl.Parent() != obj }) } properties := getApparentProperties(t, obj, typeChecker) @@ -4569,7 +4569,7 @@ func tryGetConstructorLikeCompletionContainer(contextToken *ast.Node) *ast.Const return nil } - parent := contextToken.Parent + parent := contextToken.Parent() switch contextToken.Kind { case ast.KindOpenParenToken, ast.KindCommaToken: if ast.IsConstructorDeclaration(parent) { @@ -4578,14 +4578,14 @@ func tryGetConstructorLikeCompletionContainer(contextToken *ast.Node) *ast.Const return nil default: if isConstructorParameterCompletion(contextToken) { - return parent.Parent + return parent.Parent() } } return nil } func isConstructorParameterCompletion(node *ast.Node) bool { - return node.Parent != nil && ast.IsParameterDeclaration(node.Parent) && ast.IsConstructorDeclaration(node.Parent.Parent) && + return node.Parent() != nil && ast.IsParameterDeclaration(node.Parent()) && ast.IsConstructorDeclaration(node.Parent().Parent()) && (ast.IsParameterPropertyModifier(node.Kind) || ast.IsDeclarationName(node)) } @@ -4600,12 +4600,12 @@ func tryGetObjectTypeDeclarationCompletionContainer( // class c { method() { } | method2() { } } switch location.Kind { case ast.KindSyntaxList: - if ast.IsObjectTypeDeclaration(location.Parent) { - return location.Parent + if ast.IsObjectTypeDeclaration(location.Parent()) { + return location.Parent() } return nil case ast.KindEndOfFile: - stmtList := location.Parent.StatementList() + 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 astnav.FindChildOfKind(cls, ast.KindCloseBraceToken, file) == nil { @@ -4613,7 +4613,7 @@ func tryGetObjectTypeDeclarationCompletionContainer( } } case ast.KindPrivateIdentifier: - if ast.IsPropertyDeclaration(location.Parent) { + if ast.IsPropertyDeclaration(location.Parent()) { return ast.FindAncestor(location, ast.IsClassLike) } case ast.KindIdentifier: @@ -4622,7 +4622,7 @@ func tryGetObjectTypeDeclarationCompletionContainer( return nil } // class c { public prop = c| } - if ast.IsPropertyDeclaration(location.Parent) && location.Parent.Initializer() == location { + if ast.IsPropertyDeclaration(location.Parent()) && location.Parent().Initializer() == location { return nil } // class c extends React.Component { a: () => 1\n compon| } @@ -4639,7 +4639,7 @@ func tryGetObjectTypeDeclarationCompletionContainer( // or // class C { blah \n constructor/**/ } if location.Kind == ast.KindConstructorKeyword || - (ast.IsIdentifier(contextToken) && ast.IsPropertyDeclaration(contextToken.Parent) && ast.IsClassLike(location)) { + (ast.IsIdentifier(contextToken) && ast.IsPropertyDeclaration(contextToken.Parent()) && ast.IsClassLike(location)) { return ast.FindAncestor(contextToken, ast.IsClassLike) } @@ -4651,8 +4651,8 @@ func tryGetObjectTypeDeclarationCompletionContainer( // class c { method() { } | } case ast.KindSemicolonToken, ast.KindCloseBraceToken: // class c { method() { } b| } - if isFromObjectTypeDeclaration(location) && location.Parent.Name() == location { - return location.Parent.Parent + if isFromObjectTypeDeclaration(location) && location.Parent().Name() == location { + return location.Parent().Parent() } if ast.IsObjectTypeDeclaration(location) { return location @@ -4661,8 +4661,8 @@ func tryGetObjectTypeDeclarationCompletionContainer( // class c { | // class c {getValue(): number, | } case ast.KindOpenBraceToken, ast.KindCommaToken: - if ast.IsObjectTypeDeclaration(contextToken.Parent) { - return contextToken.Parent + if ast.IsObjectTypeDeclaration(contextToken.Parent()) { + return contextToken.Parent() } return nil default: @@ -4673,14 +4673,14 @@ func tryGetObjectTypeDeclarationCompletionContainer( return location } isValidKeyword := core.IfElse( - ast.IsClassLike(contextToken.Parent.Parent), + ast.IsClassLike(contextToken.Parent().Parent()), isClassMemberCompletionKeyword, isInterfaceOrTypeLiteralCompletionKeyword, ) if isValidKeyword(contextToken.Kind) || contextToken.Kind == ast.KindAsteriskToken || ast.IsIdentifier(contextToken) && isValidKeyword(scanner.IdentifierToKeywordKind(contextToken.AsIdentifier())) { - return contextToken.Parent.Parent + return contextToken.Parent().Parent() } } @@ -4689,7 +4689,7 @@ func tryGetObjectTypeDeclarationCompletionContainer( } func isFromObjectTypeDeclaration(node *ast.Node) bool { - return node.Parent != nil && ast.IsClassOrTypeElement(node.Parent) && ast.IsObjectTypeDeclaration(node.Parent.Parent) + return node.Parent() != nil && ast.IsClassOrTypeElement(node.Parent()) && ast.IsObjectTypeDeclaration(node.Parent().Parent()) } // Filters out completion suggestions for class elements. @@ -4744,7 +4744,7 @@ func tryGetContainingJsxElement(contextToken *ast.Node, file *ast.SourceFile) *a return nil } - parent := contextToken.Parent + parent := contextToken.Parent() switch contextToken.Kind { case ast.KindGreaterThanToken, ast.KindLessThanSlashToken, ast.KindSlashToken, ast.KindIdentifier, ast.KindPropertyAccessExpression, ast.KindJsxNamespacedName, ast.KindJsxAttributes, ast.KindJsxAttribute, ast.KindJsxSpreadAttribute: @@ -4758,14 +4758,14 @@ func tryGetContainingJsxElement(contextToken *ast.Node, file *ast.SourceFile) *a } return parent } else if parent != nil && ast.IsJsxNamespacedName(parent) && - parent.Parent != nil && (parent.Parent.Kind == ast.KindJsxSelfClosingElement || parent.Parent.Kind == ast.KindJsxOpeningElement) { - return parent.Parent + parent.Parent() != nil && (parent.Parent().Kind == ast.KindJsxSelfClosingElement || parent.Parent().Kind == ast.KindJsxOpeningElement) { + return parent.Parent() } else if parent != nil && parent.Kind == ast.KindJsxAttribute { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes // properties: NodeArray - return parent.Parent.Parent + return parent.Parent().Parent() } // The context token is the closing } or " of an attribute, which means // its parent is a JsxExpression, whose parent is a JsxAttribute, @@ -4776,24 +4776,24 @@ func tryGetContainingJsxElement(contextToken *ast.Node, file *ast.SourceFile) *a // JsxOpeningLikeElement // attributes: JsxAttributes // properties: NodeArray - return parent.Parent.Parent + return parent.Parent().Parent() } case ast.KindCloseBraceToken: if parent != nil && parent.Kind == ast.KindJsxExpression && - parent.Parent != nil && parent.Parent.Kind == ast.KindJsxAttribute { + parent.Parent() != nil && parent.Parent().Kind == ast.KindJsxAttribute { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes // properties: NodeArray // each JsxAttribute can have initializer as JsxExpression - return parent.Parent.Parent.Parent + return parent.Parent().Parent().Parent() } if parent != nil && parent.Kind == ast.KindJsxSpreadAttribute { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes // properties: NodeArray - return parent.Parent.Parent + return parent.Parent().Parent() } } @@ -4968,7 +4968,7 @@ func (l *LanguageService) getJsxClosingTagCompletion( // var y = // the completion list at "1" and "2" will contain "MainComponent.Child" with a replacement span of closing tag name hasClosingAngleBracket := astnav.FindChildOfKind(jsxClosingElement, ast.KindGreaterThanToken, file) != nil - tagName := jsxClosingElement.Parent.AsJsxElement().OpeningElement.TagName() + tagName := jsxClosingElement.Parent().AsJsxElement().OpeningElement().TagName() closingTag := scanner.GetTextOfNode(tagName) fullClosingTag := closingTag + core.IfElse(hasClosingAngleBracket, "", ">") optionalReplacementSpan, fidelity := l.createLspRangeFromNode(jsxClosingElement.TagName(), file) @@ -5186,7 +5186,7 @@ func (l *LanguageService) getLabelStatementCompletions( }) } } - current = current.Parent + current = current.Parent() } return items } @@ -5225,7 +5225,7 @@ func isSolelyIdentifierDefinitionLocation( position int, typeChecker *checker.Checker, ) bool { - parent := contextToken.Parent + parent := contextToken.Parent() containingNodeKind := parent.Kind switch contextToken.Kind { case ast.KindCommaToken: @@ -5258,12 +5258,12 @@ func isSolelyIdentifierDefinitionLocation( ast.IsFunctionLikeKind(containingNodeKind) case ast.KindStaticKeyword: return containingNodeKind == ast.KindPropertyDeclaration && - !ast.IsClassLike(parent.Parent) + !ast.IsClassLike(parent.Parent()) case ast.KindDotDotDotToken: return containingNodeKind == ast.KindParameter || - (parent.Parent != nil && parent.Parent.Kind == ast.KindArrayBindingPattern) // var [...z| + (parent.Parent() != nil && parent.Parent().Kind == ast.KindArrayBindingPattern) // var [...z| case ast.KindPublicKeyword, ast.KindPrivateKeyword, ast.KindProtectedKeyword: - return containingNodeKind == ast.KindParameter && !ast.IsConstructorDeclaration(parent.Parent) + return containingNodeKind == ast.KindParameter && !ast.IsConstructorDeclaration(parent.Parent()) case ast.KindAsKeyword: return containingNodeKind == ast.KindImportSpecifier || containingNodeKind == ast.KindExportSpecifier || @@ -5320,7 +5320,7 @@ func isSolelyIdentifierDefinitionLocation( ast.KindStaticKeyword, ast.KindVarKeyword: return true case ast.KindAsyncKeyword: - return ast.IsPropertyDeclaration(contextToken.Parent) + return ast.IsPropertyDeclaration(contextToken.Parent()) } // If we are inside a class declaration, and `constructor` is totally not present, @@ -5335,7 +5335,7 @@ func isSolelyIdentifierDefinitionLocation( ancestorPropertyDeclaration := ast.FindAncestor(parent, ast.IsPropertyDeclaration) // If we are inside a class declaration and typing `constructor` after property declaration... if ancestorPropertyDeclaration != nil && contextToken != previousToken && - ast.IsClassLike(previousToken.Parent.Parent) && + ast.IsClassLike(previousToken.Parent().Parent()) && // And the cursor is at the token... position <= previousToken.End() { // If we are sure that the previous property declaration is terminated according to newline or semicolon... @@ -5363,7 +5363,7 @@ func isSolelyIdentifierDefinitionLocation( } func isVariableDeclarationListButNotTypeArgument(node *ast.Node, file *ast.SourceFile, typeChecker *checker.Checker) bool { - return node.Parent.Kind == ast.KindVariableDeclarationList && + return node.Parent().Kind == ast.KindVariableDeclarationList && !isPossiblyTypeArgumentPosition(node, file, typeChecker) } @@ -5392,27 +5392,27 @@ func isInJsxText(contextToken *ast.Node, location *ast.Node) bool { return true } - if contextToken.Kind == ast.KindGreaterThanToken && contextToken.Parent != nil { + if contextToken.Kind == ast.KindGreaterThanToken && contextToken.Parent() != nil { // /**/ /> // /**/ > // - contextToken: GreaterThanToken (before cursor) // - location: JsxSelfClosingElement or JsxOpeningElement // - contextToken.parent === location - if location == contextToken.Parent && ast.IsJsxOpeningLikeElement(location) { + if location == contextToken.Parent() && ast.IsJsxOpeningLikeElement(location) { return false } - if contextToken.Parent.Kind == ast.KindJsxOpeningElement { + if contextToken.Parent().Kind == ast.KindJsxOpeningElement { //
/**/ // - contextToken: GreaterThanToken (before cursor) // - location: JSXElement // - different parents (JSXOpeningElement, JSXElement) - return location.Parent.Kind != ast.KindJsxOpeningElement + return location.Parent().Kind != ast.KindJsxOpeningElement } - if contextToken.Parent.Kind == ast.KindJsxClosingElement || - contextToken.Parent.Kind == ast.KindJsxSelfClosingElement { - return contextToken.Parent.Parent != nil && contextToken.Parent.Parent.Kind == ast.KindJsxElement + if contextToken.Parent().Kind == ast.KindJsxClosingElement || + contextToken.Parent().Kind == ast.KindJsxSelfClosingElement { + return contextToken.Parent().Parent() != nil && contextToken.Parent().Parent().Kind == ast.KindJsxElement } } @@ -5746,7 +5746,7 @@ func (l *LanguageService) createCompletionDetailsForSymbol( func (l *LanguageService) getImportStatementCompletionInfo(contextToken *ast.Node, sourceFile *ast.SourceFile) importStatementCompletionInfo { result := importStatementCompletionInfo{} var candidate *ast.Node - parent := contextToken.Parent + parent := contextToken.Parent() switch { case ast.IsImportEqualsDeclaration(parent): // import Foo | @@ -5759,15 +5759,15 @@ func (l *LanguageService) getImportStatementCompletionInfo(contextToken *ast.Nod if contextToken.Kind != ast.KindTypeKeyword { result.keywordCompletion = ast.KindTypeKeyword } - if isModuleSpecifierMissingOrEmpty(parent.AsImportEqualsDeclaration().ModuleReference) { + if isModuleSpecifierMissingOrEmpty(parent.AsImportEqualsDeclaration().ModuleReference()) { candidate = parent } } - case couldBeTypeOnlyImportSpecifier(parent, contextToken) && canCompleteFromNamedBindings(parent.Parent): + case couldBeTypeOnlyImportSpecifier(parent, contextToken) && canCompleteFromNamedBindings(parent.Parent()): candidate = parent case ast.IsNamedImports(parent) || ast.IsNamespaceImport(parent): - if !parent.Parent.IsTypeOnly() && (contextToken.Kind == ast.KindOpenBraceToken || + if !parent.Parent().IsTypeOnly() && (contextToken.Kind == ast.KindOpenBraceToken || contextToken.Kind == ast.KindImportKeyword || contextToken.Kind == ast.KindCommaToken) { result.keywordCompletion = ast.KindTypeKeyword @@ -5778,7 +5778,7 @@ func (l *LanguageService) getImportStatementCompletionInfo(contextToken *ast.Nod result.isKeywordOnlyCompletion = true result.keywordCompletion = ast.KindFromKeyword } else { - candidate = parent.Parent.Parent + candidate = parent.Parent().Parent() } } @@ -5844,7 +5844,7 @@ func (l *LanguageService) getSingleLineReplacementSpanForImportCompletionNode(no if node.Kind == ast.KindImportDeclaration || node.Kind == ast.KindJSDocImportTag { var specifier *ast.Node if importClause := node.ImportClause(); importClause != nil { - specifier = getPotentiallyInvalidImportSpecifier(importClause.AsImportClause().NamedBindings) + specifier = getPotentiallyInvalidImportSpecifier(importClause.AsImportClause().NamedBindings()) } if specifier != nil { @@ -5853,7 +5853,7 @@ func (l *LanguageService) getSingleLineReplacementSpanForImportCompletionNode(no potentialSplitPoint = node.ModuleSpecifier() } } else { - potentialSplitPoint = node.AsImportEqualsDeclaration().ModuleReference + potentialSplitPoint = node.AsImportEqualsDeclaration().ModuleReference() } withoutModuleSpecifier := core.NewTextRange(scanner.GetTokenPosOfNode(lsutil.GetFirstToken(node, sourceFile), sourceFile, false), potentialSplitPoint.Pos()) @@ -5881,7 +5881,7 @@ func couldBeTypeOnlyImportSpecifier(importSpecifier *ast.Node, contextToken *ast } func canCompleteFromNamedBindings(namedBindings *ast.NamedImportBindings) bool { - if !isModuleSpecifierMissingOrEmpty(namedBindings.Parent.Parent.ModuleSpecifier()) || namedBindings.Parent.Name() != nil { + if !isModuleSpecifierMissingOrEmpty(namedBindings.Parent().Parent().ModuleSpecifier()) || namedBindings.Parent().Name() != nil { return false } if ast.IsNamedImports(namedBindings) { @@ -5954,7 +5954,7 @@ func tryGetTypeExpressionFromTag(tag *ast.Node) *ast.Node { if isTagWithTypeExpression(tag) { var typeExpression *ast.Node if ast.IsJSDocTemplateTag(tag) { - typeExpression = tag.AsJSDocTemplateTag().Constraint + typeExpression = tag.AsJSDocTemplateTag().Constraint() } else { typeExpression = tag.TypeExpression() } @@ -5974,7 +5974,7 @@ func isTagWithTypeExpression(tag *ast.Node) bool { ast.KindJSDocTypedefTag, ast.KindJSDocThrowsTag, ast.KindJSDocSatisfiesTag: return true case ast.KindJSDocTemplateTag: - return tag.AsJSDocTemplateTag().Constraint != nil + return tag.AsJSDocTemplateTag().Constraint() != nil default: return false } @@ -6140,12 +6140,12 @@ func getJSDocParameterCompletions( if currentToken.IsJSDoc() { jsDoc = currentToken } else { - jsDoc = currentToken.Parent + jsDoc = currentToken.Parent() } if !jsDoc.IsJSDoc() { return nil } - fun := jsDoc.Parent + fun := jsDoc.Parent() if !ast.IsFunctionLike(fun) { return nil } @@ -6155,8 +6155,8 @@ func getJSDocParameterCompletions( isSnippet := false // !!! need snippet printer paramTagCount := 0 var tags []*ast.Node - if jsDoc.AsJSDoc().Tags != nil { - tags = jsDoc.AsJSDoc().Tags.Nodes + if jsDoc.AsJSDoc().Tags() != nil { + tags = jsDoc.AsJSDoc().Tags().Nodes } for _, tag := range tags { if ast.IsJSDocParameterTag(tag) && @@ -6180,7 +6180,7 @@ func getJSDocParameterCompletions( &emitContext, paramName, param.Initializer(), - param.AsParameterDeclaration().DotDotDotToken, + param.AsParameterDeclaration().DotDotDotToken(), isJS, /*isObject*/ false, /*isSnippet*/ false, @@ -6195,7 +6195,7 @@ func getJSDocParameterCompletions( &emitContext, paramName, param.Initializer(), - param.AsParameterDeclaration().DotDotDotToken, + param.AsParameterDeclaration().DotDotDotToken(), isJS, /*isObject*/ false, /*isSnippet*/ true, @@ -6229,7 +6229,7 @@ func getJSDocParameterCompletions( paramPath, param.Name(), param.Initializer(), - param.AsParameterDeclaration().DotDotDotToken, + param.AsParameterDeclaration().DotDotDotToken(), isJS, /*isSnippet*/ false, typeChecker, @@ -6243,7 +6243,7 @@ func getJSDocParameterCompletions( paramPath, param.Name(), param.Initializer(), - param.AsParameterDeclaration().DotDotDotToken, + param.AsParameterDeclaration().DotDotDotToken(), isJS, /*isSnippet*/ true, typeChecker, @@ -6300,7 +6300,7 @@ func getJSDocParamAnnotation( t = "object" } else { if initializer != nil { - inferredType := typeChecker.GetTypeAtLocation(initializer.Parent) + inferredType := typeChecker.GetTypeAtLocation(initializer.Parent()) if inferredType.Flags()&(checker.TypeFlagsAny|checker.TypeFlagsVoid) == 0 { file := ast.GetSourceFileOfNode(initializer) quotePreference := lsutil.GetQuotePreference(file, preferences) @@ -6510,7 +6510,7 @@ func jsDocParamElementWorker( emitContext, paramName, element.Initializer(), - element.AsBindingElement().DotDotDotToken, + element.AsBindingElement().DotDotDotToken(), isJS, /*isObject*/ false, isSnippet, @@ -6530,7 +6530,7 @@ func jsDocParamElementWorker( fmt.Sprintf("%s.%s", path, propertyName), element.Name(), element.Initializer(), - element.AsBindingElement().DotDotDotToken, + element.AsBindingElement().DotDotDotToken(), isJS, isSnippet, typeChecker, @@ -6547,15 +6547,15 @@ func getJSDocParameterNameCompletions(tag *ast.JSDocParameterOrPropertyTag) []*C return nil } nameThusFar := tag.Name().Text() - jsDoc := tag.Parent - fn := jsDoc.Parent + jsDoc := tag.Parent() + fn := jsDoc.Parent() if !ast.IsFunctionLike(fn) { return nil } var tags []*ast.Node - if jsDoc.AsJSDoc().Tags != nil { - tags = jsDoc.AsJSDoc().Tags.Nodes + if jsDoc.AsJSDoc().Tags() != nil { + tags = jsDoc.AsJSDoc().Tags().Nodes } return core.MapNonNil(fn.Parameters(), func(param *ast.ParameterDeclarationNode) *CompletionItem { @@ -6592,8 +6592,8 @@ func (l *LanguageService) getExhaustiveCaseSnippets( program *compiler.Program, c *checker.Checker, ) (*lsproto.CompletionItem, error) { - clauses := caseBlock.Clauses.Nodes - switchType := c.GetTypeAtLocation(caseBlock.AsNode().Parent.Expression()) + clauses := caseBlock.Clauses().Nodes + switchType := c.GetTypeAtLocation(caseBlock.AsNode().Parent().Expression()) if switchType != nil && switchType.IsUnion() && core.Every(switchType.Types(), isLiteral) { // Collect constant values in existing clauses. tracker := newCaseClauseTracker(c, clauses) @@ -6729,17 +6729,17 @@ func typeNodeToExpression( ) *ast.Expression { switch typeNode.Kind { case ast.KindTypeReference: - typeName := typeNode.AsTypeReferenceNode().TypeName + typeName := typeNode.AsTypeReferenceNode().TypeName() return entityNameToExpression(typeName, target, quotePreference, factory) case ast.KindIndexedAccessType: objectExpression := typeNodeToExpression( - typeNode.AsIndexedAccessTypeNode().ObjectType, + typeNode.AsIndexedAccessTypeNode().ObjectType(), target, quotePreference, factory, ) indexExpression := typeNodeToExpression( - typeNode.AsIndexedAccessTypeNode().IndexType, + typeNode.AsIndexedAccessTypeNode().IndexType(), target, quotePreference, factory, @@ -6749,7 +6749,7 @@ func typeNodeToExpression( } return nil case ast.KindLiteralType: - literal := typeNode.AsLiteralTypeNode().Literal + literal := typeNode.AsLiteralTypeNode().Literal() switch literal.Kind { case ast.KindStringLiteral: expr := factory.NewStringLiteral(literal.Text(), core.IfElse(quotePreference == lsutil.QuotePreferenceSingle, ast.TokenFlagsSingleQuote, ast.TokenFlagsNone)) @@ -6762,7 +6762,7 @@ func typeNodeToExpression( } case ast.KindParenthesizedType: expr := typeNodeToExpression( - typeNode.AsParenthesizedTypeNode().Type, + typeNode.AsParenthesizedTypeNode().Type(), target, quotePreference, factory, @@ -6775,7 +6775,7 @@ func typeNodeToExpression( } return factory.NewParenthesizedExpression(expr) case ast.KindTypeQuery: - return entityNameToExpression(typeNode.AsTypeQueryNode().ExprName, target, quotePreference, factory) + return entityNameToExpression(typeNode.AsTypeQueryNode().ExprName(), target, quotePreference, factory) case ast.KindImportType: debug.Fail(`We should not get an import type after calling 'typeToAutoImportableTypeNode'.`) return nil @@ -6793,9 +6793,9 @@ func entityNameToExpression( return entityName } return factory.NewPropertyAccessExpression( - entityNameToExpression(entityName.AsQualifiedName().Left, target, quotePreference, factory), + entityNameToExpression(entityName.AsQualifiedName().Left(), target, quotePreference, factory), nil, /*questionDotToken*/ - entityName.AsQualifiedName().Right, + entityName.AsQualifiedName().Right(), ast.NodeFlagsNone, ) } diff --git a/tsc/internal/ls/definition.go b/tsc/internal/ls/definition.go index c1d3d4b6b63de..d5fd6c762d7a8 100644 --- a/tsc/internal/ls/definition.go +++ b/tsc/internal/ls/definition.go @@ -70,13 +70,13 @@ func (l *LanguageService) provideDefinitionAtPosition(ctx context.Context, progr } if ast.IsJumpStatementTarget(node) { - if label := getTargetLabel(node.Parent, node.Text()); label != nil { + if label := getTargetLabel(node.Parent(), node.Text()); label != nil { return l.createDefinitionLocations(originSelectionRange, clientSupportsLink, []*ast.Node{label}, nil /*reference*/, spanmap.FeatureDefinition) } } - if node.Kind == ast.KindCaseKeyword || node.Kind == ast.KindDefaultKeyword && ast.IsDefaultClause(node.Parent) { - if stmt := ast.FindAncestor(node.Parent, ast.IsSwitchStatement); stmt != nil { + if node.Kind == ast.KindCaseKeyword || node.Kind == ast.KindDefaultKeyword && ast.IsDefaultClause(node.Parent()) { + if stmt := ast.FindAncestor(node.Parent(), ast.IsSwitchStatement); stmt != nil { file := ast.GetSourceFileOfNode(stmt) return l.createLocationFromFileAndRange(file, scanner.GetRangeOfTokenAtPosition(file, stmt.Pos()), spanmap.FeatureDefinition) } @@ -90,7 +90,7 @@ func (l *LanguageService) provideDefinitionAtPosition(ctx context.Context, progr declarations := getDeclarationsFromLocation(c, node) calledDeclaration := tryGetSignatureDeclaration(c, node) - if calledDeclaration != nil && !(ast.IsJsxOpeningLikeElement(node.Parent) && isJsxConstructorLike(calledDeclaration)) { + if calledDeclaration != nil && !(ast.IsJsxOpeningLikeElement(node.Parent()) && isJsxConstructorLike(calledDeclaration)) { symbol := c.GetSymbolAtLocation(getDeclarationNameForKeyword(node)) if symbol != nil && core.Some(c.GetRootSymbols(symbol), func(rootSymbol *ast.Symbol) bool { return symbolMatchesSignature(rootSymbol, calledDeclaration) @@ -194,12 +194,12 @@ func combineDefinitionResponses(results []lsproto.DefinitionResponse, links bool func getDeclarationNameForKeyword(node *ast.Node) *ast.Node { if node.Kind >= ast.KindFirstKeyword && node.Kind <= ast.KindLastKeyword { - if ast.IsVariableDeclarationList(node.Parent) { - if decl := core.FirstOrNil(node.Parent.AsVariableDeclarationList().Declarations.Nodes); decl != nil && decl.Name() != nil { + if ast.IsVariableDeclarationList(node.Parent()) { + if decl := core.FirstOrNil(node.Parent().AsVariableDeclarationList().Declarations().Nodes); decl != nil && decl.Name() != nil { return decl.Name() } - } else if node.Parent.DeclarationData() != nil && node.Parent.Name() != nil && node.Pos() < node.Parent.Name().Pos() { - return node.Parent.Name() + } else if node.Parent().DeclarationData() != nil && node.Parent().Name() != nil && node.Pos() < node.Parent().Name().Pos() { + return node.Parent().Name() } } return node @@ -304,7 +304,7 @@ func (l *LanguageService) createLocationFromFileAndRange(file *ast.SourceFile, t } func getDeclarationsFromLocation(c *checker.Checker, node *ast.Node) []*ast.Node { - if ast.IsIdentifier(node) && ast.IsShorthandPropertyAssignment(node.Parent) { + if ast.IsIdentifier(node) && ast.IsShorthandPropertyAssignment(node.Parent()) { // Because name in short-hand property assignment has two different meanings: property name and property value, // using go-to-definition at such position should go to the variable declaration of the property value rather than // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition @@ -320,7 +320,7 @@ func getDeclarationsFromLocation(c *checker.Checker, node *ast.Node) []*ast.Node return core.Concatenate(declarations, contextualDeclarations) } - if ast.IsPropertyName(node) && ast.IsBindingElement(node.Parent) && ast.IsObjectBindingPattern(node.Parent.Parent) { + if ast.IsPropertyName(node) && ast.IsBindingElement(node.Parent()) && ast.IsObjectBindingPattern(node.Parent().Parent()) { // If the node is the name of a BindingElement within an ObjectBindingPattern instead of just returning the // declaration of the symbol (which is itself), we should try to get to the original type of the // ObjectBindingPattern and return the property declaration for the referenced property. @@ -330,10 +330,10 @@ func getDeclarationsFromLocation(c *checker.Checker, node *ast.Node) []*ast.Node // function bar(onfulfilled: (value: T) => void) { } // interface Test { prop1: number } // bar(({ prop1 }) => {}); => should navigate to prop1 in Test - bindingEl := node.Parent.AsBindingElement() - if bindingEl.DotDotDotToken == nil && node == core.OrElse(bindingEl.PropertyName, node.Parent.Name()) { + bindingEl := node.Parent().AsBindingElement() + if bindingEl.DotDotDotToken() == nil && node == core.OrElse(bindingEl.PropertyName(), node.Parent().Name()) { if name, ok := ast.TryGetTextOfPropertyName(node); ok { - t := c.GetTypeAtLocation(node.Parent.Parent) + t := c.GetTypeAtLocation(node.Parent().Parent()) types := []*checker.Type{t} if t.IsUnion() { types = t.Types() @@ -383,16 +383,16 @@ func getDeclarationsFromObjectLiteralElement(c *checker.Checker, node *ast.Node) return nil } - contextualType := c.GetContextualType(element.Parent, checker.ContextFlagsNone) + contextualType := c.GetContextualType(element.Parent(), checker.ContextFlagsNone) if contextualType == nil { return nil } properties := c.GetPropertySymbolsFromContextualType(element, contextualType, false /*unionSymbolOk*/) if core.Some(properties, func(p *ast.Symbol) bool { - return p.ValueDeclaration != nil && ast.IsObjectLiteralExpression(p.ValueDeclaration.Parent) && ast.IsObjectLiteralElement(p.ValueDeclaration) && p.ValueDeclaration.Name() == node + return p.ValueDeclaration != nil && ast.IsObjectLiteralExpression(p.ValueDeclaration.Parent()) && ast.IsObjectLiteralElement(p.ValueDeclaration) && p.ValueDeclaration.Name() == node }) { - if withoutNodeInferencesType := c.GetContextualType(element.Parent, checker.ContextFlagsIgnoreNodeInferences); withoutNodeInferencesType != nil { + if withoutNodeInferencesType := c.GetContextualType(element.Parent(), checker.ContextFlagsIgnoreNodeInferences); withoutNodeInferencesType != nil { if withoutNodeInferencesProperties := c.GetPropertySymbolsFromContextualType(element, withoutNodeInferencesType, false /*unionSymbolOk*/); len(withoutNodeInferencesProperties) > 0 { properties = withoutNodeInferencesProperties } @@ -411,7 +411,7 @@ func getAncestorCallLikeExpression(node *ast.Node) *ast.Node { target := ast.FindAncestor(node, func(n *ast.Node) bool { return !ast.IsRightSideOfPropertyAccess(n) }) - callLike := target.Parent + callLike := target.Parent() if callLike != nil && ast.IsCallLikeExpression(callLike) && ast.GetInvokedExpression(callLike) == target { return callLike } @@ -455,7 +455,7 @@ func symbolMatchesSignature(symbol *ast.Symbol, calledDeclaration *ast.Node) boo if symbol == calledSymbol || calledSymbol != nil && symbol == calledSymbol.Parent { return true } - parent := calledDeclaration.Parent + parent := calledDeclaration.Parent() return parent != nil && (ast.IsAssignmentExpression(parent, false /*excludeCompoundAssignment*/) || !ast.IsCallLikeExpression(parent) && ast.CanHaveSymbol(parent) && symbol == parent.Symbol()) } diff --git a/tsc/internal/ls/documenthighlights.go b/tsc/internal/ls/documenthighlights.go index d4d16be78f083..938ca6f0232a2 100644 --- a/tsc/internal/ls/documenthighlights.go +++ b/tsc/internal/ls/documenthighlights.go @@ -55,11 +55,11 @@ func (l *LanguageService) provideDocumentHighlightsAtPosition(ctx context.Contex node := astnav.GetTouchingPropertyName(sourceFile, position) // Cheap JSX check before resolving files to search. - if node.Parent != nil && (node.Parent.Kind == ast.KindJsxClosingElement || (node.Parent.Kind == ast.KindJsxOpeningElement && node.Parent.TagName() == node)) { + if node.Parent() != nil && (node.Parent().Kind == ast.KindJsxClosingElement || (node.Parent().Kind == ast.KindJsxOpeningElement && node.Parent().TagName() == node)) { var openingElement, closingElement *ast.Node - if ast.IsJsxElement(node.Parent.Parent) { - openingElement = node.Parent.Parent.AsJsxElement().OpeningElement - closingElement = node.Parent.Parent.AsJsxElement().ClosingElement + if ast.IsJsxElement(node.Parent().Parent()) { + openingElement = node.Parent().Parent().AsJsxElement().OpeningElement() + closingElement = node.Parent().Parent().AsJsxElement().ClosingElement() } var highlights []*lsproto.DocumentHighlight kind := lsproto.DocumentHighlightKindRead @@ -201,33 +201,33 @@ func (l *LanguageService) toDocumentHighlight(entry *ReferenceEntry) (string, *l func (l *LanguageService) getSyntacticDocumentHighlights(node *ast.Node, sourceFile *ast.SourceFile) []*lsproto.DocumentHighlight { switch node.Kind { case ast.KindIfKeyword, ast.KindElseKeyword: - if ast.IsIfStatement(node.Parent) { - return l.getIfElseOccurrences(node.Parent.AsIfStatement(), sourceFile) + if ast.IsIfStatement(node.Parent()) { + return l.getIfElseOccurrences(node.Parent().AsIfStatement(), sourceFile) } return nil case ast.KindReturnKeyword: - return l.useParent(node.Parent, ast.IsReturnStatement, getReturnOccurrences, sourceFile) + return l.useParent(node.Parent(), ast.IsReturnStatement, getReturnOccurrences, sourceFile) case ast.KindThrowKeyword: - return l.useParent(node.Parent, ast.IsThrowStatement, getThrowOccurrences, sourceFile) + return l.useParent(node.Parent(), ast.IsThrowStatement, getThrowOccurrences, sourceFile) case ast.KindTryKeyword, ast.KindCatchKeyword, ast.KindFinallyKeyword: var tryStatement *ast.Node if node.Kind == ast.KindCatchKeyword { - tryStatement = node.Parent.Parent + tryStatement = node.Parent().Parent() } else { - tryStatement = node.Parent + tryStatement = node.Parent() } return l.useParent(tryStatement, ast.IsTryStatement, getTryCatchFinallyOccurrences, sourceFile) case ast.KindSwitchKeyword: - return l.useParent(node.Parent, ast.IsSwitchStatement, getSwitchCaseDefaultOccurrences, sourceFile) + return l.useParent(node.Parent(), ast.IsSwitchStatement, getSwitchCaseDefaultOccurrences, sourceFile) case ast.KindCaseKeyword, ast.KindDefaultKeyword: - if ast.IsDefaultClause(node.Parent) || ast.IsCaseClause(node.Parent) { - return l.useParent(node.Parent.Parent.Parent, ast.IsSwitchStatement, getSwitchCaseDefaultOccurrences, sourceFile) + if ast.IsDefaultClause(node.Parent()) || ast.IsCaseClause(node.Parent()) { + return l.useParent(node.Parent().Parent().Parent(), ast.IsSwitchStatement, getSwitchCaseDefaultOccurrences, sourceFile) } return nil case ast.KindBreakKeyword, ast.KindContinueKeyword: - return l.useParent(node.Parent, ast.IsBreakOrContinueStatement, getBreakOrContinueStatementOccurrences, sourceFile) + return l.useParent(node.Parent(), ast.IsBreakOrContinueStatement, getBreakOrContinueStatementOccurrences, sourceFile) case ast.KindForKeyword, ast.KindWhileKeyword, ast.KindDoKeyword: - return l.useParent(node.Parent, func(n *ast.Node) bool { + return l.useParent(node.Parent(), func(n *ast.Node) bool { return ast.IsIterationStatement(n, true) }, getLoopBreakContinueOccurrences, sourceFile) case ast.KindConstructorKeyword: @@ -235,7 +235,7 @@ func (l *LanguageService) getSyntacticDocumentHighlights(node *ast.Node, sourceF case ast.KindGetKeyword, ast.KindSetKeyword: return l.getFromAllDeclarations(ast.IsAccessor, []ast.Kind{ast.KindGetKeyword, ast.KindSetKeyword}, node, sourceFile) case ast.KindAwaitKeyword: - return l.useParent(node.Parent, ast.IsAwaitExpression, getAsyncAndAwaitOccurrences, sourceFile) + return l.useParent(node.Parent(), ast.IsAwaitExpression, getAsyncAndAwaitOccurrences, sourceFile) case ast.KindAsyncKeyword: return l.highlightSpans(getAsyncAndAwaitOccurrences(node, sourceFile), sourceFile) case ast.KindYieldKeyword: @@ -243,8 +243,8 @@ func (l *LanguageService) getSyntacticDocumentHighlights(node *ast.Node, sourceF case ast.KindInKeyword, ast.KindOutKeyword: return nil default: - if ast.IsModifierKind(node.Kind) && (ast.IsDeclaration(node.Parent) || ast.IsVariableStatement(node.Parent)) { - return l.highlightSpans(getModifierOccurrences(node.Kind, node.Parent, sourceFile), sourceFile) + if ast.IsModifierKind(node.Kind) && (ast.IsDeclaration(node.Parent()) || ast.IsVariableStatement(node.Parent())) { + return l.highlightSpans(getModifierOccurrences(node.Kind, node.Parent(), sourceFile), sourceFile) } return nil } @@ -274,7 +274,7 @@ func (l *LanguageService) highlightSpans(nodes []*ast.Node, sourceFile *ast.Sour } func (l *LanguageService) getFromAllDeclarations(nodeTest func(*ast.Node) bool, keywords []ast.Kind, node *ast.Node, sourceFile *ast.SourceFile) []*lsproto.DocumentHighlight { - return l.useParent(node.Parent, nodeTest, func(decl *ast.Node, sf *ast.SourceFile) []*ast.Node { + return l.useParent(node.Parent(), nodeTest, func(decl *ast.Node, sf *ast.SourceFile) []*ast.Node { var symbolDecls []*ast.Node if ast.CanHaveSymbol(decl) { if symbol := decl.Symbol(); symbol != nil { @@ -347,10 +347,10 @@ func getIfElseKeywords(ifStatement *ast.IfStatement, sourceFile *ast.SourceFile) // ```` // // Traverse upwards through all parent if-statements linked by their else-branches. - for ast.IsIfStatement(ifStatement.Parent) { + for ast.IsIfStatement(ifStatement.Parent()) { // See if the parent's `else` is actually the current `if` statement. - parentingIf := ifStatement.Parent.AsIfStatement() - elseStatement := parentingIf.ElseStatement + parentingIf := ifStatement.Parent().AsIfStatement() + elseStatement := parentingIf.ElseStatement() if elseStatement != ifStatement.AsNode() { break } @@ -372,7 +372,7 @@ func getIfElseKeywords(ifStatement *ast.IfStatement, sourceFile *ast.SourceFile) break } } - elseStatement := ifStatement.ElseStatement + elseStatement := ifStatement.ElseStatement() if elseStatement == nil || !ast.IsIfStatement(elseStatement) { break } @@ -382,7 +382,7 @@ func getIfElseKeywords(ifStatement *ast.IfStatement, sourceFile *ast.SourceFile) } func getReturnOccurrences(node *ast.Node, sourceFile *ast.SourceFile) []*ast.Node { - funcNode := ast.FindAncestor(node.Parent, ast.IsFunctionLike) + funcNode := ast.FindAncestor(node.Parent(), ast.IsFunctionLike) if funcNode == nil { return nil } @@ -417,9 +417,9 @@ func aggregateOwnedThrowStatements(node *ast.Node, sourceFile *ast.SourceFile) [ if ast.IsTryStatement(node) { // Exceptions thrown within a try block lacking a catch clause are "owned" in the current context. statement := node.AsTryStatement() - tryBlock := statement.TryBlock - catchClause := statement.CatchClause - finallyBlock := statement.FinallyBlock + tryBlock := statement.TryBlock() + catchClause := statement.CatchClause() + finallyBlock := statement.FinallyBlock() var result []*ast.Node if catchClause != nil { @@ -489,8 +489,8 @@ func getThrowOccurrences(node *ast.Node, sourceFile *ast.SourceFile) []*ast.Node // function-block, or source file. func getThrowStatementOwner(throwStatement *ast.Node) *ast.Node { child := throwStatement - for child.Parent != nil { - parent := child.Parent + for child.Parent() != nil { + parent := child.Parent() if ast.IsFunctionBlock(parent) || parent.Kind == ast.KindSourceFile { return parent @@ -500,7 +500,7 @@ func getThrowStatementOwner(throwStatement *ast.Node) *ast.Node { // a catch clause, and if the throw-statement occurs within the try block. if ast.IsTryStatement(parent) { tryStatement := parent.AsTryStatement() - if tryStatement.TryBlock == child && tryStatement.CatchClause != nil { + if tryStatement.TryBlock() == child && tryStatement.CatchClause() != nil { return child } } @@ -519,13 +519,13 @@ func getTryCatchFinallyOccurrences(node *ast.Node, sourceFile *ast.SourceFile) [ keywords = append(keywords, token) } - if tryStatement.CatchClause != nil { + if tryStatement.CatchClause() != nil { if catchToken := astnav.FindChildOfKind(node, ast.KindCatchKeyword, sourceFile); catchToken != nil { keywords = append(keywords, catchToken) } } - if tryStatement.FinallyBlock != nil { + if tryStatement.FinallyBlock() != nil { if finallyKeyword := astnav.FindChildOfKind(node, ast.KindFinallyKeyword, sourceFile); finallyKeyword != nil { keywords = append(keywords, finallyKeyword) } @@ -543,7 +543,7 @@ func getSwitchCaseDefaultOccurrences(node *ast.Node, sourceFile *ast.SourceFile) keywords = append(keywords, token) } - clauses := switchStatement.CaseBlock.AsCaseBlock().Clauses + clauses := switchStatement.CaseBlock().AsCaseBlock().Clauses() for _, clause := range clauses.Nodes { clauseToken := lsutil.GetFirstToken(clause.AsNode(), sourceFile) if clauseToken.Kind == ast.KindCaseKeyword || clauseToken.Kind == ast.KindDefaultKeyword { @@ -610,7 +610,7 @@ func getBreakOrContinueOwner(statement *ast.Node) *ast.Node { // Whether or not a 'node' is preceded by a label of the given string. // Note: 'node' cannot be a SourceFile. func isLabeledBy(node *ast.Node, labelName string) bool { - return ast.FindAncestorOrQuit(node.Parent, func(owner *ast.Node) ast.FindAncestorResult { + return ast.FindAncestorOrQuit(node.Parent(), func(owner *ast.Node) ast.FindAncestorResult { if !ast.IsLabeledStatement(owner) { return ast.FindAncestorQuit } @@ -691,7 +691,7 @@ func getAsyncAndAwaitOccurrences(node *ast.Node, sourceFile *ast.SourceFile) []* } func getYieldOccurrences(node *ast.Node, sourceFile *ast.SourceFile) []*ast.Node { - parentFunc := ast.FindAncestor(node.Parent, ast.IsFunctionLike) + parentFunc := ast.FindAncestor(node.Parent(), ast.IsFunctionLike) if parentFunc == nil { return nil } @@ -739,7 +739,7 @@ func getModifierOccurrences(kind ast.Kind, node *ast.Node, sourceFile *ast.Sourc func getNodesToSearchForModifier(declaration *ast.Node, modifierFlag ast.ModifierFlags) []*ast.Node { var result []*ast.Node - container := declaration.Parent + container := declaration.Parent() if container == nil { return nil } @@ -756,8 +756,8 @@ func getNodesToSearchForModifier(declaration *ast.Node, modifierFlag ast.Modifie case ast.KindConstructor, ast.KindMethodDeclaration, ast.KindFunctionDeclaration: // Parameters and, if inside a class, also class members result = append(result, container.Parameters()...) - if ast.IsClassLike(container.Parent) { - result = append(result, container.Parent.Members()...) + if ast.IsClassLike(container.Parent()) { + result = append(result, container.Parent().Members()...) } return result case ast.KindClassDeclaration, ast.KindClassExpression, ast.KindInterfaceDeclaration, ast.KindTypeLiteral: diff --git a/tsc/internal/ls/file_rename.go b/tsc/internal/ls/file_rename.go index 13ffb3cb9bc15..9c57a728e4fe9 100644 --- a/tsc/internal/ls/file_rename.go +++ b/tsc/internal/ls/file_rename.go @@ -120,12 +120,12 @@ func (l *LanguageService) updateTsconfigFiles(program *compiler.Program, changeT switch propertyName { case "files", "include", "exclude": foundExactMatch := updatePathsProperty(configFile, configDir, property, changeTracker, oldToNew, l.converters, l.CaseSensitivity()) - if foundExactMatch || propertyName != "include" || !ast.IsArrayLiteralExpression(property.Initializer) { + if foundExactMatch || propertyName != "include" || !ast.IsArrayLiteralExpression(property.Initializer()) { return } if oldSpec, isDefault := commandLine.GetMatchedIncludeSpec(oldPath); oldSpec != "" && !isDefault { if newSpec, _ := commandLine.GetMatchedIncludeSpec(newPath); newSpec == "" { - elements := property.Initializer.Elements() + elements := property.Initializer().Elements() if len(elements) > 0 { newPathText := newPath.AsString() if relativePath, ok := l.CaseSensitivity().RelativePathFromDirectory(configDir, newPath); ok { @@ -140,10 +140,10 @@ func (l *LanguageService) updateTsconfigFiles(program *compiler.Program, changeT } } case "compilerOptions": - if !ast.IsObjectLiteralExpression(property.Initializer) { + if !ast.IsObjectLiteralExpression(property.Initializer()) { return } - forEachObjectProperty(property.Initializer.AsObjectLiteralExpression(), func(property *ast.PropertyAssignment, propertyName string) { + forEachObjectProperty(property.Initializer().AsObjectLiteralExpression(), func(property *ast.PropertyAssignment, propertyName string) { option := tsoptions.CommandLineCompilerOptionsMap.Get(propertyName) if option != nil { elementOption := option.Elements() @@ -153,14 +153,14 @@ func (l *LanguageService) updateTsconfigFiles(program *compiler.Program, changeT } } - if propertyName != "paths" || !ast.IsObjectLiteralExpression(property.Initializer) { + if propertyName != "paths" || !ast.IsObjectLiteralExpression(property.Initializer()) { return } - forEachObjectProperty(property.Initializer.AsObjectLiteralExpression(), func(pathsProperty *ast.PropertyAssignment, _ string) { - if !ast.IsArrayLiteralExpression(pathsProperty.Initializer) { + forEachObjectProperty(property.Initializer().AsObjectLiteralExpression(), func(pathsProperty *ast.PropertyAssignment, _ string) { + if !ast.IsArrayLiteralExpression(pathsProperty.Initializer()) { return } - for _, element := range pathsProperty.Initializer.Elements() { + for _, element := range pathsProperty.Initializer().Elements() { tryUpdateConfigString(configFile, configDir, element, changeTracker, oldToNew, l.converters, l.CaseSensitivity()) } }) @@ -170,9 +170,9 @@ func (l *LanguageService) updateTsconfigFiles(program *compiler.Program, changeT } func updatePathsProperty(configFile *ast.SourceFile, configDir tspath.RootedDirectoryPath, property *ast.PropertyAssignment, changeTracker *change.Tracker, oldToNew pathUpdater, converters *lsconv.Converters, caseSensitivity tspath.CaseSensitivity) bool { - elements := []*ast.Node{property.Initializer} - if ast.IsArrayLiteralExpression(property.Initializer) { - elements = property.Initializer.Elements() + elements := []*ast.Node{property.Initializer()} + if ast.IsArrayLiteralExpression(property.Initializer()) { + elements = property.Initializer().Elements() } foundExactMatch := false @@ -372,7 +372,7 @@ func forEachObjectProperty(objectLiteral *ast.ObjectLiteralExpression, cb func(p if objectLiteral == nil { return } - for _, property := range objectLiteral.Properties.Nodes { + for _, property := range objectLiteral.Properties().Nodes { if !ast.IsPropertyAssignment(property) { continue } diff --git a/tsc/internal/ls/findallreferences.go b/tsc/internal/ls/findallreferences.go index ea287f75d7638..8d3f96ac8c005 100644 --- a/tsc/internal/ls/findallreferences.go +++ b/tsc/internal/ls/findallreferences.go @@ -225,19 +225,19 @@ func getContextNodeForNodeEntry(node *ast.Node) *ast.Node { return getContextNode(node) } - if node.Parent == nil { + if node.Parent() == nil { return nil } - if !ast.IsDeclaration(node.Parent) && !ast.IsExportAssignment(node.Parent) { + if !ast.IsDeclaration(node.Parent()) && !ast.IsExportAssignment(node.Parent()) { // Special property assignment in javascript if ast.IsInJSFile(node) { // !!! jsdoc: check if branch still needed var binaryExpression *ast.Node - if ast.IsBinaryExpression(node.Parent) { - binaryExpression = node.Parent - } else if ast.IsAccessExpression(node.Parent) && ast.IsBinaryExpression(node.Parent.Parent) && node.Parent.Parent.AsBinaryExpression().Left == node.Parent { - binaryExpression = node.Parent.Parent + if ast.IsBinaryExpression(node.Parent()) { + binaryExpression = node.Parent() + } else if ast.IsAccessExpression(node.Parent()) && ast.IsBinaryExpression(node.Parent().Parent()) && node.Parent().Parent().AsBinaryExpression().Left() == node.Parent() { + binaryExpression = node.Parent().Parent() } if binaryExpression != nil && ast.GetAssignmentDeclarationKind(binaryExpression) != ast.JSDeclarationKindNone { return getContextNode(binaryExpression) @@ -245,11 +245,11 @@ func getContextNodeForNodeEntry(node *ast.Node) *ast.Node { } // Jsx Tags - switch node.Parent.Kind { + switch node.Parent().Kind { case ast.KindJsxOpeningElement, ast.KindJsxClosingElement: - return node.Parent.Parent + return node.Parent().Parent() case ast.KindJsxSelfClosingElement, ast.KindLabeledStatement, ast.KindBreakStatement, ast.KindContinueStatement: - return node.Parent + return node.Parent() case ast.KindStringLiteral, ast.KindNoSubstitutionTemplateLiteral: if validImport := ast.TryGetImportFromModuleSpecifier(node); validImport != nil { declOrStatement := ast.FindAncestor(validImport, func(*ast.Node) bool { @@ -265,19 +265,19 @@ func getContextNodeForNodeEntry(node *ast.Node) *ast.Node { // Handle computed property name propertyName := ast.FindAncestor(node, ast.IsComputedPropertyName) if propertyName != nil { - return getContextNode(propertyName.Parent) + return getContextNode(propertyName.Parent()) } return nil } - if node.Parent.Name() == node || // node is name of declaration, use parent - node.Parent.Kind == ast.KindConstructor || - node.Parent.Kind == ast.KindExportAssignment || + if node.Parent().Name() == node || // node is name of declaration, use parent + node.Parent().Kind == ast.KindConstructor || + node.Parent().Kind == ast.KindExportAssignment || // Property name of the import export specifier or binding pattern, use parent - ((ast.IsImportOrExportSpecifier(node.Parent) || node.Parent.Kind == ast.KindBindingElement) && node.Parent.PropertyName() == node) || + ((ast.IsImportOrExportSpecifier(node.Parent()) || node.Parent().Kind == ast.KindBindingElement) && node.Parent().PropertyName() == node) || // Is default export - (node.Kind == ast.KindDefaultKeyword && ast.HasSyntacticModifier(node.Parent, ast.ModifierFlagsExportDefault)) { - return getContextNode(node.Parent) + (node.Kind == ast.KindDefaultKeyword && ast.HasSyntacticModifier(node.Parent(), ast.ModifierFlagsExportDefault)) { + return getContextNode(node.Parent()) } return nil @@ -289,37 +289,37 @@ func getContextNode(node *ast.Node) *ast.Node { } switch node.Kind { case ast.KindVariableDeclaration: - if !ast.IsVariableDeclarationList(node.Parent) || len(node.Parent.AsVariableDeclarationList().Declarations.Nodes) != 1 { + if !ast.IsVariableDeclarationList(node.Parent()) || len(node.Parent().AsVariableDeclarationList().Declarations().Nodes) != 1 { return node - } else if ast.IsVariableStatement(node.Parent.Parent) { - return node.Parent.Parent - } else if ast.IsForInOrOfStatement(node.Parent.Parent) { - return getContextNode(node.Parent.Parent) + } else if ast.IsVariableStatement(node.Parent().Parent()) { + return node.Parent().Parent() + } else if ast.IsForInOrOfStatement(node.Parent().Parent()) { + return getContextNode(node.Parent().Parent()) } - return node.Parent + return node.Parent() case ast.KindBindingElement: - return getContextNode(node.Parent.Parent) + return getContextNode(node.Parent().Parent()) case ast.KindImportSpecifier: - return node.Parent.Parent.Parent + return node.Parent().Parent().Parent() case ast.KindExportSpecifier, ast.KindNamespaceImport: - return node.Parent.Parent + return node.Parent().Parent() case ast.KindImportClause, ast.KindNamespaceExport: - return node.Parent + return node.Parent() case ast.KindBinaryExpression: - return core.IfElse(node.Parent.Kind == ast.KindExpressionStatement, node.Parent, node) + return core.IfElse(node.Parent().Kind == ast.KindExpressionStatement, node.Parent(), node) case ast.KindForOfStatement, ast.KindForInStatement: // !!! not implemented return nil case ast.KindPropertyAssignment, ast.KindShorthandPropertyAssignment: - if ast.IsArrayLiteralOrObjectLiteralDestructuringPattern(node.Parent) { - return getContextNode(ast.FindAncestor(node.Parent, func(node *ast.Node) bool { + if ast.IsArrayLiteralOrObjectLiteralDestructuringPattern(node.Parent()) { + return getContextNode(ast.FindAncestor(node.Parent(), func(node *ast.Node) bool { return node.Kind == ast.KindBinaryExpression || ast.IsForInOrOfStatement(node) })) } @@ -365,8 +365,8 @@ func isValidReferencePosition(node *ast.Node, searchSymbolName string) bool { return len(node.Text()) == len(searchSymbolName) && (isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfModuleDeclaration(node) || isExpressionOfExternalModuleImportEqualsDeclaration(node) || - ast.IsCallExpression(node.Parent) && ast.IsBindableObjectDefinePropertyCall(node.Parent) && node.Parent.Arguments()[1] == node || - ast.IsImportOrExportSpecifier(node.Parent)) + ast.IsCallExpression(node.Parent()) && ast.IsBindableObjectDefinePropertyCall(node.Parent()) && node.Parent().Arguments()[1] == node || + ast.IsImportOrExportSpecifier(node.Parent())) case ast.KindNumericLiteral: return isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && len(node.Text()) == len(searchSymbolName) case ast.KindDefaultKeyword: @@ -383,13 +383,13 @@ func skipPastExportOrImportSpecifierOrUnion(symbol *ast.Symbol, node *ast.Node, if node == nil { return nil } - parent := node.Parent + parent := node.Parent() if parent.Kind == ast.KindExportSpecifier && useLocalSymbolForExportSpecifier { return getLocalSymbolForExportSpecifier(node, symbol, parent.AsExportSpecifier(), checker) } // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. return core.FirstNonNil(symbol.Declarations, func(decl *ast.Node) *ast.Symbol { - if decl.Parent == nil { + if decl.Parent() == nil { // Ignore UMD module and global merge and CJS module end exports symbols if symbol.Flags&(ast.SymbolFlagsTransient|ast.SymbolFlagsModuleExports) != 0 { return nil @@ -397,8 +397,8 @@ func skipPastExportOrImportSpecifierOrUnion(symbol *ast.Symbol, node *ast.Node, // Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here. panic(fmt.Sprintf("Unexpected symbol at %s: %s", node.Kind.String(), symbol.Name)) } - if decl.Parent.Kind == ast.KindTypeLiteral && decl.Parent.Parent.Kind == ast.KindUnionType { - return checker.GetPropertyOfType(checker.GetTypeFromTypeNode(decl.Parent.Parent), symbol.Name) + if decl.Parent().Kind == ast.KindTypeLiteral && decl.Parent().Parent().Kind == ast.KindUnionType { + return checker.GetPropertyOfType(checker.GetTypeFromTypeNode(decl.Parent().Parent()), symbol.Name) } return nil }) @@ -562,13 +562,13 @@ func isDefinitionVisible(emitResolver *checker.EmitResolver, declaration *ast.No if emitResolver.IsDeclarationVisible(declaration) { return true } - if declaration.Parent == nil { + if declaration.Parent() == nil { return false } // Variable initializers are visible if variable is visible - if ast.HasInitializer(declaration.Parent) && declaration.Parent.Initializer() == declaration { - return isDefinitionVisible(emitResolver, declaration.Parent) + if ast.HasInitializer(declaration.Parent()) && declaration.Parent().Initializer() == declaration { + return isDefinitionVisible(emitResolver, declaration.Parent()) } // Handle some exceptions here like arrow function, members of class and object literal expression which are technically not visible but we want the definition to be determined by its parent @@ -591,7 +591,7 @@ func isDefinitionVisible(emitResolver *checker.EmitResolver, declaration *ast.No ast.KindClassExpression, ast.KindArrowFunction, ast.KindFunctionExpression: - return isDefinitionVisible(emitResolver, declaration.Parent) + return isDefinitionVisible(emitResolver, declaration.Parent()) default: return false } @@ -1087,11 +1087,11 @@ func isDeclarationOfSymbol(node *ast.Node, target *ast.Symbol) bool { if decl := ast.GetDeclarationFromName(node); decl != nil { source = decl } else if node.Kind == ast.KindDefaultKeyword { - source = node.Parent + source = node.Parent() } else if ast.IsLiteralComputedPropertyDeclarationName(node) { - source = node.Parent.Parent - } else if node.Kind == ast.KindConstructorKeyword && ast.IsConstructorDeclaration(node.Parent) { - source = node.Parent.Parent + source = node.Parent().Parent() + } else if node.Kind == ast.KindConstructorKeyword && ast.IsConstructorDeclaration(node.Parent()) { + source = node.Parent().Parent() } // !!! @@ -1251,8 +1251,8 @@ func (l *LanguageService) GetSignatureUsages(ctx context.Context, signatureDecl called := ast.ClimbPastPropertyAccess(node) var callExpr *ast.Node - if called.Parent != nil && ast.IsCallExpression(called.Parent) && called.Parent.Expression() == called { - callExpr = called.Parent + if called.Parent() != nil && ast.IsCallExpression(called.Parent()) && called.Parent().Expression() == called { + callExpr = called.Parent() } result = append(result, SignatureUsage{ @@ -1309,7 +1309,7 @@ func (l *LanguageService) getReferencedSymbolsForNode(ctx context.Context, posit } // constructors should use the class symbol, detected by name, if present - symbol := checker.GetSymbolAtLocation(core.IfElse(node.Kind == ast.KindConstructor && node.Parent.Name() != nil, node.Parent.Name(), node)) + symbol := checker.GetSymbolAtLocation(core.IfElse(node.Kind == ast.KindConstructor && node.Parent().Name() != nil, node.Parent().Name(), node)) // Could not find a symbol e.g. unknown identifier if symbol == nil { // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. @@ -1392,8 +1392,8 @@ func (l *LanguageService) getReferencesForStringLiteral( } func isStringLiteralPropertyReference(node *ast.StringLiteralLike, checker *checker.Checker) bool { - if ast.IsPropertySignatureDeclaration(node.Parent) { - return checker.GetPropertyOfType(checker.GetTypeAtLocation(node.Parent.Parent), node.Text()) != nil + if ast.IsPropertySignatureDeclaration(node.Parent()) { + return checker.GetPropertyOfType(checker.GetTypeAtLocation(node.Parent().Parent()), node.Text()) != nil } return false } @@ -1421,7 +1421,7 @@ func (l *LanguageService) getReferencedSymbolsForModuleIfDeclaredBySourceFile(ct func getReferencedSymbolsSpecial(node *ast.Node, sourceFiles []*ast.SourceFile) []*SymbolAndEntries { if isTypeKeyword(node.Kind) { // A void expression (i.e., `void foo()`) is not special, but the `void` type is. - if node.Kind == ast.KindVoidKeyword && node.Parent.Kind == ast.KindVoidExpression { + if node.Kind == ast.KindVoidKeyword && node.Parent().Kind == ast.KindVoidExpression { return nil } @@ -1440,11 +1440,11 @@ func getReferencedSymbolsSpecial(node *ast.Node, sourceFiles []*ast.SourceFile) ) } - if ast.IsImportMeta(node.Parent) && node.Parent.Name() == node { + if ast.IsImportMeta(node.Parent()) && node.Parent().Name() == node { return getAllReferencesForImportMeta(sourceFiles) } - if node.Kind == ast.KindStaticKeyword && node.Parent.Kind == ast.KindClassStaticBlockDeclaration { + if node.Kind == ast.KindStaticKeyword && node.Parent().Kind == ast.KindClassStaticBlockDeclaration { return []*SymbolAndEntries{{definition: &Definition{Kind: definitionKindKeyword, node: node}, references: []*ReferenceEntry{newNodeEntry(node)}}} } @@ -1452,15 +1452,15 @@ func getReferencedSymbolsSpecial(node *ast.Node, sourceFiles []*ast.SourceFile) if isJumpStatementTarget(node) { // if we have a label definition, look within its statement for references, if not, then // the label is undefined and we have no results.. - if labelDefinition := getTargetLabel(node.Parent, node.Text()); labelDefinition != nil { - return getLabelReferencesInNode(labelDefinition.Parent, labelDefinition) + if labelDefinition := getTargetLabel(node.Parent(), node.Text()); labelDefinition != nil { + return getLabelReferencesInNode(labelDefinition.Parent(), labelDefinition) } return nil } if isLabelOfLabeledStatement(node) { // it is a label definition and not a target, search within the parent labeledStatement - return getLabelReferencesInNode(node.Parent, node) + return getLabelReferencesInNode(node.Parent(), node) } if isThis(node) { @@ -1493,7 +1493,7 @@ func getReferencesForThisKeyword(thisOrSuperKeyword *ast.Node, sourceFiles []*as // Whether 'this' occurs in a static context within a class. staticFlag := ast.ModifierFlagsStatic isParameterName := func(node *ast.Node) bool { - return node.Kind == ast.KindIdentifier && node.Parent.Kind == ast.KindParameter && node.Parent.Name() == node + return node.Kind == ast.KindIdentifier && node.Parent().Kind == ast.KindParameter && node.Parent().Name() == node } switch searchSpaceNode.Kind { @@ -1501,11 +1501,11 @@ func getReferencesForThisKeyword(thisOrSuperKeyword *ast.Node, sourceFiles []*as ast.KindPropertyDeclaration, ast.KindPropertySignature, ast.KindConstructor, ast.KindGetAccessor, ast.KindSetAccessor: if (searchSpaceNode.Kind == ast.KindMethodDeclaration || searchSpaceNode.Kind == ast.KindMethodSignature) && ast.IsObjectLiteralMethod(searchSpaceNode) { staticFlag &= searchSpaceNode.ModifierFlags() - searchSpaceNode = searchSpaceNode.Parent // re-assign to be the owning object literals + searchSpaceNode = searchSpaceNode.Parent() // re-assign to be the owning object literals break } staticFlag &= searchSpaceNode.ModifierFlags() - searchSpaceNode = searchSpaceNode.Parent // re-assign to be the owning class + searchSpaceNode = searchSpaceNode.Parent() // re-assign to be the owning class case ast.KindSourceFile: if ast.IsExternalModule(searchSpaceNode.AsSourceFile()) || isParameterName(thisOrSuperKeyword) { return nil @@ -1542,7 +1542,7 @@ func getReferencesForThisKeyword(thisOrSuperKeyword *ast.Node, sourceFiles []*as case ast.KindClassExpression, ast.KindClassDeclaration, ast.KindObjectLiteralExpression: // Make sure the container belongs to the same class/object literals // and has the appropriate static modifier from the original container. - return container.Parent != nil && ast.CanHaveSymbol(container.Parent) && searchSpaceNode.Symbol() == container.Parent.Symbol() && ast.IsStatic(container) == (staticFlag != ast.ModifierFlagsNone) + return container.Parent() != nil && ast.CanHaveSymbol(container.Parent()) && searchSpaceNode.Symbol() == container.Parent().Symbol() && ast.IsStatic(container) == (staticFlag != ast.ModifierFlagsNone) case ast.KindSourceFile: return container.Kind == ast.KindSourceFile && !ast.IsExternalModule(container.AsSourceFile()) && !isParameterName(node) } @@ -1554,7 +1554,7 @@ func getReferencesForThisKeyword(thisOrSuperKeyword *ast.Node, sourceFiles []*as ) thisParameter := core.FirstNonNil(references, func(ref *ReferenceEntry) *ast.Node { - if ref.node.Parent.Kind == ast.KindParameter { + if ref.node.Parent().Kind == ast.KindParameter { return ref.node } return nil @@ -1576,7 +1576,7 @@ func getReferencesForSuperKeyword(superKeyword *ast.Node) []*SymbolAndEntries { switch searchSpaceNode.Kind { case ast.KindPropertyDeclaration, ast.KindPropertySignature, ast.KindMethodDeclaration, ast.KindMethodSignature, ast.KindConstructor, ast.KindGetAccessor, ast.KindSetAccessor: staticFlag &= searchSpaceNode.ModifierFlags() - searchSpaceNode = searchSpaceNode.Parent // re-assign to be the owning class + searchSpaceNode = searchSpaceNode.Parent() // re-assign to be the owning class default: return nil } @@ -1592,7 +1592,7 @@ func getReferencesForSuperKeyword(superKeyword *ast.Node) []*SymbolAndEntries { // If we have a 'super' container, we must have an enclosing class. // Now make sure the owning class is the same as the search-space // and has the same static qualifier as the original 'super's owner. - if container != nil && ast.IsStatic(container) == (staticFlag != ast.ModifierFlagsNone) && container.Parent.Symbol() == searchSpaceNode.Symbol() { + if container != nil && ast.IsStatic(container) == (staticFlag != ast.ModifierFlagsNone) && container.Parent().Symbol() == searchSpaceNode.Symbol() { return newNodeEntry(node) } return nil @@ -1604,7 +1604,7 @@ func getReferencesForSuperKeyword(superKeyword *ast.Node) []*SymbolAndEntries { func getAllReferencesForImportMeta(sourceFiles []*ast.SourceFile) []*SymbolAndEntries { references := core.FlatMap(sourceFiles, func(sourceFile *ast.SourceFile) []*ReferenceEntry { return core.MapNonNil(getPossibleSymbolReferenceNodes(sourceFile, "meta", sourceFile.AsNode()), func(node *ast.Node) *ReferenceEntry { - parent := node.Parent + parent := node.Parent() if ast.IsImportMeta(parent) { return newNodeEntry(parent) } @@ -1721,7 +1721,7 @@ func getReferencesForNonModule(referencedFile *ast.SourceFile, program *compiler } func getMergedAliasedSymbolOfNamespaceExportDeclaration(node *ast.Node, symbol *ast.Symbol, checker *checker.Checker) *ast.Symbol { - if node.Parent != nil && node.Parent.Kind == ast.KindNamespaceExportDeclaration { + if node.Parent() != nil && node.Parent().Kind == ast.KindNamespaceExportDeclaration { if aliasedSymbol, ok := checker.ResolveAlias(symbol); ok { targetSymbol := checker.GetMergedSymbol(aliasedSymbol) if aliasedSymbol != targetSymbol { @@ -1739,12 +1739,12 @@ func (l *LanguageService) getReferencedSymbolsForModule(checker *checker.Checker references := core.MapNonNil(moduleRefs, func(reference ModuleReference) *ReferenceEntry { switch reference.kind { case ModuleReferenceKindImport: - parent := reference.literal.Parent + parent := reference.literal.Parent() if ast.IsLiteralTypeNode(parent) { - importType := parent.Parent + importType := parent.Parent() if ast.IsImportTypeNode(importType) { importTypeNode := importType.AsImportTypeNode() - if excludeImportTypeOfExportEquals && importTypeNode.Qualifier == nil { + if excludeImportTypeOfExportEquals && importTypeNode.Qualifier() == nil { return nil } } @@ -1805,8 +1805,8 @@ func (l *LanguageService) getReferencedSymbolsForModule(checker *checker.Checker if sourceFilesSet.Has(sourceFile.FileName()) { var node *ast.Node // At `module.exports = ...`, reference node is `module` - if ast.IsBinaryExpression(decl) && ast.IsPropertyAccessExpression(decl.AsBinaryExpression().Left) { - node = decl.AsBinaryExpression().Left.Expression() + if ast.IsBinaryExpression(decl) && ast.IsPropertyAccessExpression(decl.AsBinaryExpression().Left()) { + node = decl.AsBinaryExpression().Left().Expression() } else if ast.IsExportAssignment(decl) { // Find the export keyword node = astnav.FindChildOfKind(decl, ast.KindExportKeyword, sourceFile) @@ -1840,8 +1840,8 @@ func getSpecialSearchKind(node *ast.Node) string { case ast.KindConstructor, ast.KindConstructorKeyword: return "constructor" case ast.KindIdentifier: - if ast.IsClassLike(node.Parent) { - debug.Assert(node.Parent.Name() == node) + if ast.IsClassLike(node.Parent()) { + debug.Assert(node.Parent().Name() == node) return "class" } fallthrough @@ -2034,7 +2034,7 @@ func isMethodOrAccessor(node *ast.Node) bool { } func tryGetClassByExtendingIdentifier(node *ast.Node) *ast.ClassLikeDeclaration { - return ast.TryGetClassExtendingExpressionWithTypeArguments(ast.ClimbPastPropertyAccess(node).Parent) + return ast.TryGetClassExtendingExpressionWithTypeArguments(ast.ClimbPastPropertyAccess(node).Parent()) } func getClassConstructorSymbol(classSymbol *ast.Symbol) *ast.Symbol { @@ -2109,7 +2109,7 @@ func forEachDescendantOfKind(node *ast.Node, kind ast.Kind, action func(*ast.Nod func (state *refState) addImplementationReferences(refNode *ast.Node, addRef func(*ast.Node)) { // Check if we found a function/propertyAssignment/method with an implementation or initializer - if ast.IsDeclarationName(refNode) && isImplementation(refNode.Parent) { + if ast.IsDeclarationName(refNode) && isImplementation(refNode.Parent()) { addRef(refNode) return } @@ -2118,7 +2118,7 @@ func (state *refState) addImplementationReferences(refNode *ast.Node, addRef fun return } - if refNode.Parent.Kind == ast.KindShorthandPropertyAssignment { + if refNode.Parent().Kind == ast.KindShorthandPropertyAssignment { // Go ahead and dereference the shorthand assignment by going to its definition getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addRef) } @@ -2133,14 +2133,14 @@ func (state *refState) addImplementationReferences(refNode *ast.Node, addRef fun // If we got a type reference, try and see if the reference applies to any expressions that can implement an interface // Find the first node whose parent isn't a type node -- i.e., the highest type node. typeNode := ast.FindAncestor(refNode, func(a *ast.Node) bool { - return !ast.IsQualifiedName(a.Parent) && !ast.IsTypeNode(a.Parent) && !ast.IsTypeElement(a.Parent) + return !ast.IsQualifiedName(a.Parent()) && !ast.IsTypeNode(a.Parent()) && !ast.IsTypeElement(a.Parent()) }) - if typeNode == nil || typeNode.Parent.Type() == nil { + if typeNode == nil || typeNode.Parent().Type() == nil { return } - typeHavingNode := typeNode.Parent + typeHavingNode := typeNode.Parent() if typeHavingNode.Type() == typeNode && state.seenContainingTypeReferences.AddIfAbsent(typeHavingNode) { addIfImplementation := func(e *ast.Expression) { if isImplementationExpression(e) { @@ -2244,7 +2244,7 @@ func (state *refState) getReferencesAtLocation(sourceFile *ast.SourceFile, posit return } - parent := referenceLocation.Parent + parent := referenceLocation.Parent() if parent.Kind == ast.KindImportSpecifier && parent.PropertyName() == referenceLocation { // This is added through `singleReferences` in ImportsResult. If we happen to see it again, don't add it again. return @@ -2273,9 +2273,9 @@ func (state *refState) getReferencesAtLocation(sourceFile *ast.SourceFile, posit } // Use the parent symbol if the location is commonjs require syntax on javascript files only. - if ast.IsInJSFile(referenceLocation) && referenceLocation.Parent.Kind == ast.KindBindingElement && - ast.IsVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.Parent.Parent.Parent) { - referenceSymbol = referenceLocation.Parent.Symbol() + if ast.IsInJSFile(referenceLocation) && referenceLocation.Parent().Kind == ast.KindBindingElement && + ast.IsVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.Parent().Parent().Parent()) { + referenceSymbol = referenceLocation.Parent().Symbol() // The parent will not have a symbol if it's an ObjectBindingPattern (when destructuring is used). In // this case, just skip it, since the bound identifiers are not an alias of the import. if referenceSymbol == nil { @@ -2295,7 +2295,7 @@ func (state *refState) addConstructorReferences(referenceLocation *ast.Node, sym return state.referenceAdder(search.symbol) } - if ast.IsClassLike(referenceLocation.Parent) { + if ast.IsClassLike(referenceLocation.Parent()) { // This is the class declaration containing the constructor. sourceFile := ast.GetSourceFileOfNode(referenceLocation) findOwnConstructorReferences(search.symbol, sourceFile, func(n *ast.Node) { @@ -2317,7 +2317,7 @@ func (state *refState) addClassStaticThisReferences(referenceLocation *ast.Node, state.addReference(referenceLocation, symbol, entryKindNode) } - classLike := referenceLocation.Parent + classLike := referenceLocation.Parent() if state.options.use == referenceUseRename || !ast.IsClassLike(classLike) { return } @@ -2386,8 +2386,8 @@ func (state *refState) getReferencesAtExportSpecifier( ) { debug.Assert(!alwaysGetReferences || state.options.useAliasesForRename, "If alwaysGetReferences is true, then prefix/suffix text must be enabled") - exportDeclaration := exportSpecifier.Parent.Parent.AsExportDeclaration() - propertyName := exportSpecifier.PropertyName + exportDeclaration := exportSpecifier.Parent().Parent().AsExportDeclaration() + propertyName := exportSpecifier.PropertyName() name := exportSpecifier.Name() localSymbol := getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker) @@ -2409,7 +2409,7 @@ func (state *refState) getReferencesAtExportSpecifier( } else if referenceLocation == propertyName.AsNode() { // For `export { foo as bar } from "baz"`, "`foo`" will be added from the singleReferences for import searches of the original export. // For `export { foo as bar };`, where `foo` is a local, so add it now. - if exportDeclaration.ModuleSpecifier == nil { + if exportDeclaration.ModuleSpecifier() == nil { addRef() } @@ -2440,7 +2440,7 @@ func (state *refState) getReferencesAtExportSpecifier( } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. - if search.comingFrom != ImpExpKindExport && exportDeclaration.ModuleSpecifier != nil && propertyName == nil && !isForRenameWithPrefixAndSuffixText(state.options) { + if search.comingFrom != ImpExpKindExport && exportDeclaration.ModuleSpecifier() != nil && propertyName == nil && !isForRenameWithPrefixAndSuffixText(state.options) { imported := state.checker.GetExportSpecifierLocalTargetSymbol(exportSpecifier.AsNode()) if imported != nil { state.searchForImportedSymbol(imported) @@ -2503,11 +2503,11 @@ func (state *refState) shouldAddSingleReference(singleRef *ast.Node) bool { return true } // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;` - if !ast.IsIdentifier(singleRef) && !ast.IsImportOrExportSpecifier(singleRef.Parent) { + if !ast.IsIdentifier(singleRef) && !ast.IsImportOrExportSpecifier(singleRef.Parent()) { return false } // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. - return !(ast.IsImportOrExportSpecifier(singleRef.Parent) && ast.ModuleExportNameIsDefault(singleRef)) + return !(ast.IsImportOrExportSpecifier(singleRef.Parent()) && ast.ModuleExportNameIsDefault(singleRef)) } func (state *refState) hasMatchingMeaning(referenceLocation *ast.Node) bool { @@ -2633,7 +2633,7 @@ func (state *refState) forEachRelatedSymbol( * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. */ - shorthandValueSymbol := state.checker.GetShorthandAssignmentValueSymbol(location.Parent) + shorthandValueSymbol := state.checker.GetShorthandAssignmentValueSymbol(location.Parent()) // gets the local symbol if shorthandValueSymbol != nil && isForRenamePopulateSearchSymbolSet { // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property. @@ -2642,7 +2642,7 @@ func (state *refState) forEachRelatedSymbol( // If the location is in a context sensitive location (i.e. in an object literal) try // to get a contextual type for it, and add the property symbol from the contextual // type to the search set - if contextualType := state.checker.GetContextualType(containingObjectLiteralElement.Parent, checker.ContextFlagsNone); contextualType != nil { + if contextualType := state.checker.GetContextualType(containingObjectLiteralElement.Parent(), checker.ContextFlagsNone); contextualType != nil { symbols := state.checker.GetPropertySymbolsFromContextualType(containingObjectLiteralElement, contextualType, true /*unionSymbolOk*/) for _, sym := range symbols { if res := fromRoot(sym); res != nil { @@ -2676,7 +2676,7 @@ func (state *refState) forEachRelatedSymbol( return res, entryKindNode } - if symbol.ValueDeclaration != nil && ast.IsParameterPropertyDeclaration(symbol.ValueDeclaration, symbol.ValueDeclaration.Parent) { + if symbol.ValueDeclaration != nil && ast.IsParameterPropertyDeclaration(symbol.ValueDeclaration, symbol.ValueDeclaration.Parent()) { paramProp1, paramProp2 := state.checker.GetSymbolsOfParameterPropertyDeclaration(symbol.ValueDeclaration, symbol.Name) debug.Assert( paramProp1.Flags&ast.SymbolFlagsFunctionScopedVariable != 0 && paramProp2.Flags&ast.SymbolFlagsClassMember != 0, @@ -2698,10 +2698,10 @@ func (state *refState) forEachRelatedSymbol( if !isForRenamePopulateSearchSymbolSet { var bindingElementPropertySymbol *ast.Symbol if onlyIncludeBindingElementAtReferenceLocation { - if !isObjectBindingElementWithoutPropertyName(location.Parent) { + if !isObjectBindingElementWithoutPropertyName(location.Parent()) { return nil, entryKindNone } - bindingElementPropertySymbol = getPropertySymbolFromBindingElement(state.checker, location.Parent) + bindingElementPropertySymbol = getPropertySymbolFromBindingElement(state.checker, location.Parent()) } else { bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, state.checker) } diff --git a/tsc/internal/ls/folding.go b/tsc/internal/ls/folding.go index 7bb733b65f29a..34443d8c6948a 100644 --- a/tsc/internal/ls/folding.go +++ b/tsc/internal/ls/folding.go @@ -208,17 +208,17 @@ func visitNode(ctx context.Context, n *ast.Node, depthRemaining int, sourceFile if (!ast.IsBinaryExpression(n) && ast.IsDeclaration(n)) || ast.IsVariableStatement(n) || ast.IsReturnStatement(n) || ast.IsCallOrNewExpression(n) || n.Kind == ast.KindEndOfFile { foldingRange = append(foldingRange, addOutliningForLeadingCommentsForNode(ctx, n, sourceFile, l)...) } - if ast.IsFunctionLike(n) && n.Parent != nil && ast.IsBinaryExpression(n.Parent) && n.Parent.AsBinaryExpression().Left != nil && ast.IsPropertyAccessExpression(n.Parent.AsBinaryExpression().Left) { - foldingRange = append(foldingRange, addOutliningForLeadingCommentsForNode(ctx, n.Parent.AsBinaryExpression().Left, sourceFile, l)...) + if ast.IsFunctionLike(n) && n.Parent() != nil && ast.IsBinaryExpression(n.Parent()) && n.Parent().AsBinaryExpression().Left() != nil && ast.IsPropertyAccessExpression(n.Parent().AsBinaryExpression().Left()) { + foldingRange = append(foldingRange, addOutliningForLeadingCommentsForNode(ctx, n.Parent().AsBinaryExpression().Left(), sourceFile, l)...) } if ast.IsBlock(n) { - statements := n.AsBlock().Statements + statements := n.AsBlock().Statements() if statements != nil { foldingRange = append(foldingRange, addOutliningForLeadingCommentsForPos(ctx, statements.End(), sourceFile, l)...) } } if ast.IsModuleBlock(n) { - statements := n.AsModuleBlock().Statements + statements := n.AsModuleBlock().Statements() if statements != nil { foldingRange = append(foldingRange, addOutliningForLeadingCommentsForPos(ctx, statements.End(), sourceFile, l)...) } @@ -226,11 +226,11 @@ func visitNode(ctx context.Context, n *ast.Node, depthRemaining int, sourceFile if ast.IsClassLike(n) || ast.IsInterfaceDeclaration(n) { var members *ast.NodeList if ast.IsClassDeclaration(n) { - members = n.AsClassDeclaration().Members + members = n.AsClassDeclaration().Members() } else if ast.IsClassExpression(n) { - members = n.AsClassExpression().Members + members = n.AsClassExpression().Members() } else { - members = n.AsInterfaceDeclaration().Members + members = n.AsInterfaceDeclaration().Members() } if members != nil { foldingRange = append(foldingRange, addOutliningForLeadingCommentsForPos(ctx, members.End(), sourceFile, l)...) @@ -261,19 +261,19 @@ func visitNode(ctx context.Context, n *ast.Node, depthRemaining int, sourceFile foldingRange = append(foldingRange, visitNode(ctx, typeArg, depthRemaining, sourceFile, l)...) } } - } else if ast.IsIfStatement(n) && n.AsIfStatement().ElseStatement != nil && ast.IsIfStatement(n.AsIfStatement().ElseStatement) { + } else if ast.IsIfStatement(n) && n.AsIfStatement().ElseStatement() != nil && ast.IsIfStatement(n.AsIfStatement().ElseStatement()) { // Consider an 'else if' to be on the same depth as the 'if'. ifStatement := n.AsIfStatement() expressionNodes := visitNode(ctx, n.Expression(), depthRemaining, sourceFile, l) if expressionNodes != nil { foldingRange = append(foldingRange, expressionNodes...) } - thenNode := visitNode(ctx, ifStatement.ThenStatement, depthRemaining, sourceFile, l) + thenNode := visitNode(ctx, ifStatement.ThenStatement(), depthRemaining, sourceFile, l) if thenNode != nil { foldingRange = append(foldingRange, thenNode...) } depthRemaining++ - elseNode := visitNode(ctx, ifStatement.ElseStatement, depthRemaining, sourceFile, l) + elseNode := visitNode(ctx, ifStatement.ElseStatement(), depthRemaining, sourceFile, l) if elseNode != nil { foldingRange = append(foldingRange, elseNode...) } @@ -400,21 +400,21 @@ func parseRegionDelimiter(lineText string) *regionDelimiterResult { func getOutliningSpanForNode(ctx context.Context, n *ast.Node, sourceFile *ast.SourceFile, l *LanguageService) *lsproto.FoldingRange { switch n.Kind { case ast.KindBlock: - if ast.IsFunctionLike(n.Parent) { - return functionSpan(ctx, n.Parent, n, sourceFile, l) + if ast.IsFunctionLike(n.Parent()) { + return functionSpan(ctx, n.Parent(), n, sourceFile, l) } // Check if the block is standalone, or 'attached' to some parent statement. // If the latter, we want to collapse the block, but consider its hint span // to be the entire span of the parent. - switch n.Parent.Kind { + switch n.Parent().Kind { case ast.KindDoStatement, ast.KindForInStatement, ast.KindForOfStatement, ast.KindForStatement, ast.KindIfStatement, ast.KindWhileStatement, ast.KindWithStatement, ast.KindCatchClause: return spanForNode(ctx, n, ast.KindOpenBraceToken, true /*useFullStart*/, sourceFile, l) case ast.KindTryStatement: // Could be the try-block, or the finally-block. - tryStatement := n.Parent.AsTryStatement() - if tryStatement.TryBlock == n { + tryStatement := n.Parent().AsTryStatement() + if tryStatement.TryBlock() == n { return spanForNode(ctx, n, ast.KindOpenBraceToken, true /*useFullStart*/, sourceFile, l) - } else if tryStatement.FinallyBlock == n { + } else if tryStatement.FinallyBlock() == n { if span := spanForNode(ctx, n, ast.KindOpenBraceToken, true /*useFullStart*/, sourceFile, l); span != nil { return span } @@ -434,13 +434,13 @@ func getOutliningSpanForNode(ctx context.Context, n *ast.Node, sourceFile *ast.S case ast.KindClassDeclaration, ast.KindClassExpression, ast.KindInterfaceDeclaration, ast.KindEnumDeclaration, ast.KindCaseBlock, ast.KindTypeLiteral, ast.KindObjectBindingPattern: return spanForNode(ctx, n, ast.KindOpenBraceToken, true /*useFullStart*/, sourceFile, l) case ast.KindTupleType: - return spanForNode(ctx, n, ast.KindOpenBracketToken, !ast.IsTupleTypeNode(n.Parent) /*useFullStart*/, sourceFile, l) + return spanForNode(ctx, n, ast.KindOpenBracketToken, !ast.IsTupleTypeNode(n.Parent()) /*useFullStart*/, sourceFile, l) case ast.KindCaseClause, ast.KindDefaultClause: - return spanForNodeArray(ctx, n.AsCaseOrDefaultClause().Statements, sourceFile, l) + return spanForNodeArray(ctx, n.AsCaseOrDefaultClause().Statements(), sourceFile, l) case ast.KindObjectLiteralExpression: - return spanForNode(ctx, n, ast.KindOpenBraceToken, !ast.IsArrayLiteralExpression(n.Parent) && !ast.IsCallExpression(n.Parent) /*useFullStart*/, sourceFile, l) + return spanForNode(ctx, n, ast.KindOpenBraceToken, !ast.IsArrayLiteralExpression(n.Parent()) && !ast.IsCallExpression(n.Parent()) /*useFullStart*/, sourceFile, l) case ast.KindArrayLiteralExpression: - return spanForNode(ctx, n, ast.KindOpenBracketToken, !ast.IsArrayLiteralExpression(n.Parent) && !ast.IsCallExpression(n.Parent) /*useFullStart*/, sourceFile, l) + return spanForNode(ctx, n, ast.KindOpenBracketToken, !ast.IsArrayLiteralExpression(n.Parent()) && !ast.IsCallExpression(n.Parent()) /*useFullStart*/, sourceFile, l) case ast.KindJsxElement, ast.KindJsxFragment: return spanForJSXElement(ctx, n, sourceFile, l) case ast.KindJsxSelfClosingElement, ast.KindJsxOpeningElement: @@ -448,7 +448,7 @@ func getOutliningSpanForNode(ctx context.Context, n *ast.Node, sourceFile *ast.S case ast.KindTemplateExpression, ast.KindNoSubstitutionTemplateLiteral: return spanForTemplateLiteral(ctx, n, sourceFile, l) case ast.KindArrayBindingPattern: - return spanForNode(ctx, n, ast.KindOpenBracketToken, !ast.IsBindingElement(n.Parent) /*useFullStart*/, sourceFile, l) + return spanForNode(ctx, n, ast.KindOpenBracketToken, !ast.IsBindingElement(n.Parent()) /*useFullStart*/, sourceFile, l) case ast.KindArrowFunction: return spanForArrowFunction(ctx, n, sourceFile, l) case ast.KindCallExpression: @@ -465,11 +465,11 @@ func spanForImportExportElements(ctx context.Context, node *ast.Node, sourceFile var elements *ast.NodeList switch node.Kind { case ast.KindNamedImports: - elements = node.AsNamedImports().Elements + elements = node.AsNamedImports().Elements() case ast.KindNamedExports: - elements = node.AsNamedExports().Elements + elements = node.AsNamedExports().Elements() case ast.KindImportAttributes: - elements = node.AsImportAttributes().Attributes + elements = node.AsImportAttributes().Attributes() } if elements == nil || len(elements.Nodes) == 0 { return nil @@ -495,7 +495,7 @@ func spanForParenthesizedExpression(ctx context.Context, node *ast.Node, sourceF } func spanForCallExpression(ctx context.Context, node *ast.Node, sourceFile *ast.SourceFile, l *LanguageService) *lsproto.FoldingRange { - if node.AsCallExpression().Arguments == nil || len(node.AsCallExpression().Arguments.Nodes) == 0 { + if node.AsCallExpression().Arguments() == nil || len(node.AsCallExpression().Arguments().Nodes) == 0 { return nil } openToken := astnav.FindChildOfKind(node, ast.KindOpenParenToken, sourceFile) @@ -509,10 +509,10 @@ func spanForCallExpression(ctx context.Context, node *ast.Node, sourceFile *ast. func spanForArrowFunction(ctx context.Context, node *ast.Node, sourceFile *ast.SourceFile, l *LanguageService) *lsproto.FoldingRange { arrowFunctionNode := node.AsArrowFunction() - if ast.IsBlock(arrowFunctionNode.Body) || ast.IsParenthesizedExpression(arrowFunctionNode.Body) || printer.PositionsAreOnSameLine(arrowFunctionNode.Body.Pos(), arrowFunctionNode.Body.End(), sourceFile) { + if ast.IsBlock(arrowFunctionNode.Body()) || ast.IsParenthesizedExpression(arrowFunctionNode.Body()) || printer.PositionsAreOnSameLine(arrowFunctionNode.Body().Pos(), arrowFunctionNode.Body().End(), sourceFile) { return nil } - textRange, fidelity := l.createFoldingRangeFromBounds(arrowFunctionNode.Body.Pos(), arrowFunctionNode.Body.End(), sourceFile) + textRange, fidelity := l.createFoldingRangeFromBounds(arrowFunctionNode.Body().Pos(), arrowFunctionNode.Body().End(), sourceFile) if fidelity.IsNone() { return nil } @@ -529,17 +529,17 @@ func spanForTemplateLiteral(ctx context.Context, node *ast.Node, sourceFile *ast func spanForJSXElement(ctx context.Context, node *ast.Node, sourceFile *ast.SourceFile, l *LanguageService) *lsproto.FoldingRange { if node.Kind == ast.KindJsxElement { jsxElement := node.AsJsxElement() - textRange, fidelity := l.createFoldingRangeFromBounds(astnav.GetStartOfNode(jsxElement.OpeningElement, sourceFile, false /*includeJSDoc*/), jsxElement.ClosingElement.End(), sourceFile) + textRange, fidelity := l.createFoldingRangeFromBounds(astnav.GetStartOfNode(jsxElement.OpeningElement(), sourceFile, false /*includeJSDoc*/), jsxElement.ClosingElement().End(), sourceFile) if fidelity.IsNone() { return nil } - tagName := scanner.GetTextOfNode(jsxElement.OpeningElement.TagName()) + tagName := scanner.GetTextOfNode(jsxElement.OpeningElement().TagName()) bannerText := "<" + tagName + ">..." return createFoldingRange(ctx, textRange, "", bannerText) } // JsxFragment jsxFragment := node.AsJsxFragment() - textRange, fidelity := l.createFoldingRangeFromBounds(astnav.GetStartOfNode(jsxFragment.OpeningFragment, sourceFile, false /*includeJSDoc*/), jsxFragment.ClosingFragment.End(), sourceFile) + textRange, fidelity := l.createFoldingRangeFromBounds(astnav.GetStartOfNode(jsxFragment.OpeningFragment(), sourceFile, false /*includeJSDoc*/), jsxFragment.ClosingFragment().End(), sourceFile) if fidelity.IsNone() { return nil } @@ -549,9 +549,9 @@ func spanForJSXElement(ctx context.Context, node *ast.Node, sourceFile *ast.Sour func spanForJSXAttributes(ctx context.Context, node *ast.Node, sourceFile *ast.SourceFile, l *LanguageService) *lsproto.FoldingRange { var attributes *ast.JsxAttributesNode if node.Kind == ast.KindJsxSelfClosingElement { - attributes = node.AsJsxSelfClosingElement().Attributes + attributes = node.AsJsxSelfClosingElement().Attributes() } else { - attributes = node.AsJsxOpeningElement().Attributes + attributes = node.AsJsxOpeningElement().Attributes() } if len(attributes.Properties()) == 0 { return nil diff --git a/tsc/internal/ls/format.go b/tsc/internal/ls/format.go index 36027e5146ae0..66868cca08a39 100644 --- a/tsc/internal/ls/format.go +++ b/tsc/internal/ls/format.go @@ -262,7 +262,7 @@ func getRangeOfEnclosingComment( ) *ast.CommentRange { jsdoc := ast.FindAncestor(tokenAtPosition, (*ast.Node).IsJSDoc) if jsdoc != nil { - tokenAtPosition = jsdoc.Parent + tokenAtPosition = jsdoc.Parent() } tokenStart := astnav.GetStartOfNode(tokenAtPosition, file, false /*includeJSDoc*/) if tokenStart <= position && position < tokenAtPosition.End() { diff --git a/tsc/internal/ls/hover.go b/tsc/internal/ls/hover.go index 249960e8021dd..2dad40355a7c4 100644 --- a/tsc/internal/ls/hover.go +++ b/tsc/internal/ls/hover.go @@ -312,7 +312,7 @@ func getDocumentationFromDeclaration(getMappedLocation documentationLocationMapp if jsdoc := getJSDocOrTag(c, declaration, &collections.Set[*ast.Symbol]{}); jsdoc != nil && !(declaration.Flags&ast.NodeFlagsReparsed == 0 && containsTypedefTag(jsdoc)) { writeComments(getMappedLocation, &b, c, jsdoc.Comments(), isMarkdown) if jsdoc.Kind == ast.KindJSDoc && !commentOnly { - if tags := jsdoc.AsJSDoc().Tags; tags != nil { + if tags := jsdoc.AsJSDoc().Tags(); tags != nil { for _, tag := range tags.Nodes { if tag.Kind == ast.KindJSDocTypeTag || tag.Kind == ast.KindJSDocTypedefTag || tag.Kind == ast.KindJSDocCallbackTag { continue @@ -365,16 +365,16 @@ func getDocumentationFromDeclaration(getMappedLocation documentationLocationMapp } else { writeCode(&b, "tsx", commentText) } - } else if tag.Kind == ast.KindJSDocSeeTag && tag.AsJSDocSeeTag().NameExpression != nil { + } else if tag.Kind == ast.KindJSDocSeeTag && tag.AsJSDocSeeTag().NameExpression() != nil { b.WriteString(" — ") - writeNameLink(getMappedLocation, &b, c, tag.AsJSDocSeeTag().NameExpression.Name(), "", false /*quote*/, isMarkdown) + writeNameLink(getMappedLocation, &b, c, tag.AsJSDocSeeTag().NameExpression().Name(), "", false /*quote*/, isMarkdown) if len(comments) != 0 { b.WriteString(" ") writeComments(getMappedLocation, &b, c, comments, isMarkdown) } - } else if tag.Kind == ast.KindJSDocThrowsTag && tag.AsJSDocThrowsTag().TypeExpression != nil { + } else if tag.Kind == ast.KindJSDocThrowsTag && tag.AsJSDocThrowsTag().TypeExpression() != nil { b.WriteString(" — ") - b.WriteString(scanner.GetTextOfNode(tag.AsJSDocThrowsTag().TypeExpression)) + b.WriteString(scanner.GetTextOfNode(tag.AsJSDocThrowsTag().TypeExpression())) if len(comments) != 0 { b.WriteString(" ") writeComments(getMappedLocation, &b, c, comments, isMarkdown) @@ -405,7 +405,7 @@ func shouldGetType(node *ast.Node) bool { case ast.KindIdentifier: // If we're in a JSDoc node with no associated symbol, no binding has taken place for the node and // we can't answer questions about types of declaration nodes (such as property declarations). - return !(node.Flags&ast.NodeFlagsJSDoc != 0 && ast.IsDeclarationName(node)) && !ast.IsLabelName(node) && !ast.IsTagName(node) && !ast.IsConstTypeReference(node.Parent) + return !(node.Flags&ast.NodeFlagsJSDoc != 0 && ast.IsDeclarationName(node)) && !ast.IsLabelName(node) && !ast.IsTagName(node) && !ast.IsConstTypeReference(node.Parent()) case ast.KindThisKeyword, ast.KindThisType, ast.KindSuperKeyword, ast.KindNamedTupleMember: return true case ast.KindMetaProperty: @@ -522,12 +522,12 @@ func getQuickInfoAndDeclarationAtLocation(c *checker.Checker, symbol *ast.Symbol } writeModuleImportAttributes := func(symbol *ast.Symbol) { declaration := core.Find(symbol.Declarations, func(declaration *ast.Node) bool { - return ast.IsModuleDeclaration(declaration) && declaration.AsModuleDeclaration().Attributes != nil + return ast.IsModuleDeclaration(declaration) && declaration.AsModuleDeclaration().Attributes() != nil }) if declaration == nil { return } - attributes := declaration.AsModuleDeclaration().Attributes + attributes := declaration.AsModuleDeclaration().Attributes() emitContext := getEmitContext() emitContext.SetEmitFlags(attributes, printer.EFSingleLine) p := printer.NewPrinter(printer.PrinterOptions{NewLine: core.NewLineKindLF}, printer.PrintHandlers{}, emitContext) @@ -781,9 +781,9 @@ func getQuickInfoAndDeclarationAtLocation(c *checker.Checker, symbol *ast.Symbol if flags&(ast.SymbolFlagsFunction|ast.SymbolFlagsMethod) != 0 { isMethod := flags&ast.SymbolFlagsMethod != 0 prefix := core.IfElse(isMethod, "method", "function ") - if ast.IsIdentifier(node) && (ast.IsFunctionLikeDeclaration(node.Parent) || ast.IsMethodSignatureDeclaration(node.Parent)) && node.Parent.Name() == node && slices.Contains(symbol.Declarations, node.Parent) { - setDeclaration(node.Parent) - signatures := []*checker.Signature{c.GetSignatureFromDeclaration(node.Parent)} + if ast.IsIdentifier(node) && (ast.IsFunctionLikeDeclaration(node.Parent()) || ast.IsMethodSignatureDeclaration(node.Parent())) && node.Parent().Name() == node && slices.Contains(symbol.Declarations, node.Parent()) { + setDeclaration(node.Parent()) + signatures := []*checker.Signature{c.GetSignatureFromDeclaration(node.Parent())} writeSignatures(signatures, prefix, isMethod, symbol) } else { signatures := getSignaturesAtLocation(c, symbol, checker.SignatureKindCall, node) @@ -800,9 +800,9 @@ func getQuickInfoAndDeclarationAtLocation(c *checker.Checker, symbol *ast.Symbol if node.Kind == ast.KindThisKeyword || ast.IsThisInTypeQuery(node) { writeNewLine() dpw.WriteKeyword("this") - } else if node.Kind == ast.KindConstructorKeyword && (ast.IsConstructorDeclaration(node.Parent) || ast.IsConstructSignatureDeclaration(node.Parent)) { - setDeclaration(node.Parent) - signatures := []*checker.Signature{c.GetSignatureFromDeclaration(node.Parent)} + } else if node.Kind == ast.KindConstructorKeyword && (ast.IsConstructorDeclaration(node.Parent()) || ast.IsConstructSignatureDeclaration(node.Parent())) { + setDeclaration(node.Parent()) + signatures := []*checker.Signature{c.GetSignatureFromDeclaration(node.Parent())} writeSignatures(signatures, "constructor ", false, symbol) } else { var signatures []*checker.Signature @@ -881,7 +881,7 @@ func getQuickInfoAndDeclarationAtLocation(c *checker.Checker, symbol *ast.Symbol dpw.WritePunctuation("(") dpw.Write("type parameter") dpw.WritePunctuation(") ") - if ast.IsIdentifier(node) && ast.IsTypeReferenceNode(node.Parent) && checker.IsDistributedTypeParameter(c.GetTypeAtLocation(node.Parent)) { + if ast.IsIdentifier(node) && ast.IsTypeReferenceNode(node.Parent()) && checker.IsDistributedTypeParameter(c.GetTypeAtLocation(node.Parent())) { dpw.WritePunctuation("(") dpw.Write("distributed") dpw.WritePunctuation(") ") @@ -905,8 +905,8 @@ func getQuickInfoAndDeclarationAtLocation(c *checker.Checker, symbol *ast.Symbol } else { // Method/function type parameter decl := ast.GetDeclarationOfKind(symbol, ast.KindTypeParameter) - if decl != nil && decl.Parent != nil { - declaration := decl.Parent + if decl != nil && decl.Parent() != nil { + declaration := decl.Parent() if ast.IsFunctionLike(declaration) { dpw.WriteKeyword(" in ") if declaration.Kind == ast.KindConstructSignature { @@ -938,8 +938,8 @@ func getQuickInfoAndDeclarationAtLocation(c *checker.Checker, symbol *ast.Symbol writeTypeParams(c.GetTypeAliasTypeParameters(symbol)) dpw.WriteOperator(" = ") var typeAliasType *checker.Type - if node.Parent != nil && ast.IsConstTypeReference(node.Parent) { - typeAliasType = c.GetTypeAtLocation(node.Parent) + if node.Parent() != nil && ast.IsConstTypeReference(node.Parent()) { + typeAliasType = c.GetTypeAtLocation(node.Parent()) } else { typeAliasType = c.GetDeclaredTypeOfSymbol(symbol) } @@ -962,27 +962,27 @@ func typeParameterToString(c *checker.Checker, t *checker.Type, enclosingDeclara } func getNodeForQuickInfo(node *ast.Node) *ast.Node { - if node.Parent == nil { + if node.Parent() == nil { return node } - if ast.IsNewExpression(node.Parent) && node.Pos() == node.Parent.Pos() { - return node.Parent.Expression() + if ast.IsNewExpression(node.Parent()) && node.Pos() == node.Parent().Pos() { + return node.Parent().Expression() } - if ast.IsNamedTupleMember(node.Parent) && node.Pos() == node.Parent.Pos() { - return node.Parent + if ast.IsNamedTupleMember(node.Parent()) && node.Pos() == node.Parent().Pos() { + return node.Parent() } - if ast.IsImportMeta(node.Parent) && node.Parent.Name() == node { - return node.Parent + if ast.IsImportMeta(node.Parent()) && node.Parent().Name() == node { + return node.Parent() } - if ast.IsJsxNamespacedName(node.Parent) { - return node.Parent + if ast.IsJsxNamespacedName(node.Parent()) { + return node.Parent() } return node } func getSymbolAtLocationForQuickInfo(c *checker.Checker, node *ast.Node) *ast.Symbol { if objectElement := getContainingObjectLiteralElement(node); objectElement != nil { - if contextualType := c.GetContextualType(objectElement.Parent, checker.ContextFlagsNone); contextualType != nil { + if contextualType := c.GetContextualType(objectElement.Parent(), checker.ContextFlagsNone); contextualType != nil { if properties := c.GetPropertySymbolsFromContextualType(objectElement, contextualType, false /*unionSymbolOk*/); len(properties) == 1 { return properties[0] } @@ -1006,18 +1006,18 @@ func getCallOrNewExpression(node *ast.Node) *ast.Node { if ast.IsSourceFile(node) { return nil } - if ast.IsPropertyAccessExpression(node.Parent) && node.Parent.Name() == node { - node = node.Parent + if ast.IsPropertyAccessExpression(node.Parent()) && node.Parent().Name() == node { + node = node.Parent() } - if (ast.IsCallExpression(node.Parent) || ast.IsNewExpression(node.Parent)) && node.Parent.Expression() == node { - return node.Parent + if (ast.IsCallExpression(node.Parent()) || ast.IsNewExpression(node.Parent())) && node.Parent().Expression() == node { + return node.Parent() } return nil } func containsTypedefTag(jsdoc *ast.Node) bool { if jsdoc.Kind == ast.KindJSDoc { - if tags := jsdoc.AsJSDoc().Tags; tags != nil { + if tags := jsdoc.AsJSDoc().Tags(); tags != nil { for _, tag := range tags.Nodes { if tag.Kind == ast.KindJSDocTypedefTag || tag.Kind == ast.KindJSDocCallbackTag { return true @@ -1157,9 +1157,9 @@ func writeEntityNameParts(b *strings.Builder, node *ast.Node) { case ast.KindIdentifier: b.WriteString(node.Text()) case ast.KindQualifiedName: - writeEntityNameParts(b, node.AsQualifiedName().Left) + writeEntityNameParts(b, node.AsQualifiedName().Left()) b.WriteByte('.') - writeEntityNameParts(b, node.AsQualifiedName().Right) + writeEntityNameParts(b, node.AsQualifiedName().Right()) case ast.KindPropertyAccessExpression: writeEntityNameParts(b, node.Expression()) b.WriteByte('.') diff --git a/tsc/internal/ls/importTracker.go b/tsc/internal/ls/importTracker.go index d87a0d1255768..976347cae7530 100644 --- a/tsc/internal/ls/importTracker.go +++ b/tsc/internal/ls/importTracker.go @@ -124,7 +124,7 @@ func forEachImport(program *compiler.Program, sourceFile *ast.SourceFile, action } case ast.KindImportEqualsDeclaration: if isExternalModuleImportEquals(node) { - action(node, node.AsImportEqualsDeclaration().ModuleReference.Expression()) + action(node, node.AsImportEqualsDeclaration().ModuleReference().Expression()) } } return false @@ -145,12 +145,12 @@ func getSourceFileLikeForImportDeclaration(node *ast.Node) *ast.Node { if ast.IsCallExpression(node) || ast.IsJSDocImportTag(node) { return ast.GetSourceFileOfNode(node).AsNode() } - parent := node.Parent + parent := node.Parent() if ast.IsSourceFile(parent) { return parent } - debug.Assert(ast.IsModuleBlock(parent) && isAmbientModuleDeclaration(parent.Parent)) - return parent.Parent + debug.Assert(ast.IsModuleBlock(parent) && isAmbientModuleDeclaration(parent.Parent())) + return parent.Parent() } func isAmbientModuleDeclaration(node *ast.Node) bool { @@ -216,7 +216,7 @@ func getImportersForExport( if ast.HasSyntacticModifier(node, ast.ModifierFlagsExport) { return true } - node = node.Parent + node = node.Parent() } return false } @@ -255,7 +255,7 @@ func getImportersForExport( if ast.IsImportCall(direct) { handleImportCall(direct) } else if !isAvailableThroughGlobal { - parent := direct.Parent + parent := direct.Parent() if exportInfo.exportKind == ExportKindExportEquals && ast.IsVariableDeclaration(parent) { name := parent.Name() if ast.IsIdentifier(name) { @@ -270,7 +270,7 @@ func getImportersForExport( case ast.KindImportDeclaration, ast.KindJSImportDeclaration, ast.KindJSDocImportTag: directImports = append(directImports, direct) if importClause := direct.ImportClause(); importClause != nil { - if namedBindings := importClause.AsImportClause().NamedBindings; namedBindings != nil && ast.IsNamespaceImport(namedBindings) { + if namedBindings := importClause.AsImportClause().NamedBindings(); namedBindings != nil && ast.IsNamespaceImport(namedBindings) { handleNamespaceImport(direct, namedBindings.Name(), false /*isReExport*/, true /*alreadyAddedDirect*/) break } @@ -280,7 +280,7 @@ func getImportersForExport( // Add a check for indirect uses to handle synthetic default imports } case ast.KindExportDeclaration: - exportClause := direct.AsExportDeclaration().ExportClause + exportClause := direct.AsExportDeclaration().ExportClause() if exportClause == nil { // This is `export * from "foo"`, so imports of this module may import the export too. handleDirectImports(getContainingModuleSymbol(direct, checker)) @@ -293,7 +293,7 @@ func getImportersForExport( } case ast.KindImportType: // Only check for typeof import('xyz') - if !isAvailableThroughGlobal && direct.AsImportTypeNode().IsTypeOf && direct.AsImportTypeNode().Qualifier == nil && isExported(direct, false) { + if !isAvailableThroughGlobal && direct.AsImportTypeNode().IsTypeOf && direct.AsImportTypeNode().Qualifier() == nil && isExported(direct, false) { addIndirectUser(ast.GetSourceFileOfNode(direct).AsNode(), true /*addTransitiveDependencies*/) } directImports = append(directImports, direct) @@ -333,7 +333,7 @@ func findNamespaceReExports(sourceFileLike *ast.Node, name *ast.Node, checker *c if !ast.IsExportDeclaration(statement) { return false } - exportClause := statement.AsExportDeclaration().ExportClause + exportClause := statement.AsExportDeclaration().ExportClause() 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 @@ -413,13 +413,13 @@ func getSearchesFromDirectImports( return } if ast.IsImportTypeNode(decl) { - if qualifier := decl.AsImportTypeNode().Qualifier; qualifier != nil { + if qualifier := decl.AsImportTypeNode().Qualifier(); qualifier != nil { firstIdentifier := ast.GetFirstIdentifier(qualifier) if firstIdentifier.Text() == ast.SymbolName(exportSymbol) { singleReferences = append(singleReferences, firstIdentifier) } } else if exportKind == ExportKindExportEquals { - singleReferences = append(singleReferences, decl.AsImportTypeNode().Argument.AsLiteralTypeNode().Literal) + singleReferences = append(singleReferences, decl.AsImportTypeNode().Argument().AsLiteralTypeNode().Literal()) } return } @@ -428,13 +428,13 @@ func getSearchesFromDirectImports( return } if ast.IsExportDeclaration(decl) { - if exportClause := decl.AsExportDeclaration().ExportClause; exportClause != nil && ast.IsNamedExports(exportClause) { + if exportClause := decl.AsExportDeclaration().ExportClause(); exportClause != nil && ast.IsNamedExports(exportClause) { searchForNamedImport(exportClause) } return } if importClause := decl.ImportClause(); importClause != nil { - if namedBindings := importClause.AsImportClause().NamedBindings; namedBindings != nil { + if namedBindings := importClause.AsImportClause().NamedBindings(); namedBindings != nil { switch namedBindings.Kind { case ast.KindNamespaceImport: handleNamespaceImportLike(namedBindings.Name()) @@ -517,8 +517,8 @@ func getImportOrExportSymbol(node *ast.Node, symbol *ast.Symbol, checker *checke return exportInfo(sym, kind) } - parent := node.Parent - grandparent := parent.Parent + parent := node.Parent() + grandparent := parent.Parent() if symbol.ExportSymbol != nil { if ast.IsPropertyAccessExpression(parent) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. @@ -533,7 +533,7 @@ func getImportOrExportSymbol(node *ast.Node, symbol *ast.Symbol, checker *checke exportNode := getExportNode(parent, node) switch { case exportNode != nil && (ast.HasSyntacticModifier(exportNode, ast.ModifierFlagsExport) || ast.IsImplicitlyExportedJSDocDeclaration(exportNode)): - if ast.IsImportEqualsDeclaration(exportNode) && exportNode.AsImportEqualsDeclaration().ModuleReference == node { + if ast.IsImportEqualsDeclaration(exportNode) && exportNode.AsImportEqualsDeclaration().ModuleReference() == node { // We're at `Y` in `export import X = Y`. This is not the exported symbol, the left-hand-side is. So treat this as an import statement. if comingFromExport { return nil @@ -635,8 +635,8 @@ func getExportNode(parent *ast.Node, node *ast.Node) *ast.Node { declaration = ast.WalkUpBindingElementsAndPatterns(parent) } if declaration != nil { - if parent.Name() == node && !ast.IsCatchClause(declaration.Parent) && ast.IsVariableStatement(declaration.Parent.Parent) { - return declaration.Parent.Parent + if parent.Name() == node && !ast.IsCatchClause(declaration.Parent()) && ast.IsVariableStatement(declaration.Parent().Parent()) { + return declaration.Parent().Parent() } return nil } @@ -644,7 +644,7 @@ func getExportNode(parent *ast.Node, node *ast.Node) *ast.Node { } func isNodeImport(node *ast.Node) bool { - parent := node.Parent + parent := node.Parent() switch parent.Kind { case ast.KindImportEqualsDeclaration: return parent.Name() == node && isExternalModuleImportEquals(parent) @@ -655,13 +655,13 @@ func isNodeImport(node *ast.Node) bool { debug.Assert(parent.Name() == node) return true case ast.KindBindingElement: - return ast.IsInJSFile(node) && ast.IsVariableDeclarationInitializedToBareOrAccessedRequire(parent.Parent.Parent) + return ast.IsInJSFile(node) && ast.IsVariableDeclarationInitializedToBareOrAccessedRequire(parent.Parent().Parent()) } return false } func isExternalModuleImportEquals(node *ast.Node) bool { - moduleReference := node.AsImportEqualsDeclaration().ModuleReference + moduleReference := node.AsImportEqualsDeclaration().ModuleReference() return ast.IsExternalModuleReference(moduleReference) && moduleReference.Expression().Kind == ast.KindStringLiteral } @@ -670,12 +670,12 @@ func skipExportSpecifierSymbol(symbol *ast.Symbol, checker *checker.Checker) *as // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. for _, declaration := range symbol.Declarations { switch { - case ast.IsExportSpecifier(declaration) && declaration.PropertyName() == nil && declaration.Parent.Parent.ModuleSpecifier() == nil: + case ast.IsExportSpecifier(declaration) && declaration.PropertyName() == nil && declaration.Parent().Parent().ModuleSpecifier() == nil: return core.OrElse(checker.GetExportSpecifierLocalTargetSymbol(declaration), symbol) case ast.IsPropertyAccessExpression(declaration) && ast.IsModuleExportsAccessExpression(declaration.Expression()) && !ast.IsPrivateIdentifier(declaration.Name()): // Export of form 'module.exports.propName = expr'; return checker.GetSymbolAtLocation(declaration) - case ast.IsShorthandPropertyAssignment(declaration) && ast.IsBinaryExpression(declaration.Parent.Parent) && ast.GetAssignmentDeclarationKind(declaration.Parent.Parent) == ast.JSDeclarationKindModuleExports: + case ast.IsShorthandPropertyAssignment(declaration) && ast.IsBinaryExpression(declaration.Parent().Parent()) && ast.GetAssignmentDeclarationKind(declaration.Parent().Parent()) == ast.JSDeclarationKindModuleExports: return checker.GetExportSpecifierLocalTargetSymbol(declaration.Name()) } } @@ -692,7 +692,7 @@ func getExportEqualsLocalSymbol(importedSymbol *ast.Symbol, checker *checker.Che case ast.IsExportAssignment(decl): return decl.Expression().Symbol() case ast.IsBinaryExpression(decl): - return decl.AsBinaryExpression().Right.Symbol() + return decl.AsBinaryExpression().Right().Symbol() case ast.IsSourceFile(decl): return decl.Symbol() } diff --git a/tsc/internal/ls/inlay_hints.go b/tsc/internal/ls/inlay_hints.go index c84c1394fccea..79a2a56dc4b95 100644 --- a/tsc/internal/ls/inlay_hints.go +++ b/tsc/internal/ls/inlay_hints.go @@ -423,7 +423,7 @@ func isHintableDeclaration(node *ast.VariableOrParameterDeclaration) bool { func isHintableLiteral(node *ast.Node) bool { switch node.Kind { case ast.KindPrefixUnaryExpression: - operand := node.AsPrefixUnaryExpression().Operand + operand := node.AsPrefixUnaryExpression().Operand() return ast.IsLiteralExpression(operand) || ast.IsIdentifier(operand) && ast.IsInfinityOrNaNString(operand.Text()) case ast.KindTrueKeyword, ast.KindFalseKeyword, ast.KindNullKeyword, ast.KindNoSubstitutionTemplateLiteral, ast.KindTemplateExpression: @@ -476,20 +476,20 @@ func (s *inlayHintState) getInlayHintLabelParts(node *ast.Node, idToSymbol map[* parts = append(parts, &lsproto.InlayHintLabelPart{Value: identifierText}) } case ast.KindQualifiedName: - visitForDisplayParts(node.AsQualifiedName().Left) + visitForDisplayParts(node.AsQualifiedName().Left()) parts = append(parts, &lsproto.InlayHintLabelPart{Value: "."}) - visitForDisplayParts(node.AsQualifiedName().Right) + visitForDisplayParts(node.AsQualifiedName().Right()) case ast.KindTypePredicate: - if node.AsTypePredicateNode().AssertsModifier != nil { + if node.AsTypePredicateNode().AssertsModifier() != nil { parts = append(parts, &lsproto.InlayHintLabelPart{Value: "asserts "}) } - visitForDisplayParts(node.AsTypePredicateNode().ParameterName) + visitForDisplayParts(node.AsTypePredicateNode().ParameterName()) if node.Type() != nil { parts = append(parts, &lsproto.InlayHintLabelPart{Value: " is "}) visitForDisplayParts(node.Type()) } case ast.KindTypeReference: - visitForDisplayParts(node.AsTypeReferenceNode().TypeName) + visitForDisplayParts(node.AsTypeReferenceNode().TypeName()) if len(node.TypeArguments()) > 0 { parts = append(parts, &lsproto.InlayHintLabelPart{Value: "<"}) visitDisplayPartList(node.TypeArguments(), ",") @@ -500,19 +500,19 @@ func (s *inlayHintState) getInlayHintLabelParts(node *ast.Node, idToSymbol map[* visitDisplayPartList(node.ModifierNodes(), "") } visitForDisplayParts(node.Name()) - if node.AsTypeParameterDeclaration().Constraint != nil { + if node.AsTypeParameterDeclaration().Constraint() != nil { parts = append(parts, &lsproto.InlayHintLabelPart{Value: " extends "}) - visitForDisplayParts(node.AsTypeParameterDeclaration().Constraint) + visitForDisplayParts(node.AsTypeParameterDeclaration().Constraint()) } - if node.AsTypeParameterDeclaration().DefaultType != nil { + if node.AsTypeParameterDeclaration().DefaultType() != nil { parts = append(parts, &lsproto.InlayHintLabelPart{Value: " = "}) - visitForDisplayParts(node.AsTypeParameterDeclaration().DefaultType) + visitForDisplayParts(node.AsTypeParameterDeclaration().DefaultType()) } case ast.KindParameter: if len(node.ModifierNodes()) > 0 { visitDisplayPartList(node.ModifierNodes(), " ") } - if node.AsParameterDeclaration().DotDotDotToken != nil { + if node.AsParameterDeclaration().DotDotDotToken() != nil { parts = append(parts, &lsproto.InlayHintLabelPart{Value: "..."}) } visitForDisplayParts(node.Name()) @@ -530,7 +530,7 @@ func (s *inlayHintState) getInlayHintLabelParts(node *ast.Node, idToSymbol map[* visitForDisplayParts(node.Type()) case ast.KindTypeQuery: parts = append(parts, &lsproto.InlayHintLabelPart{Value: "typeof "}) - visitForDisplayParts(node.AsTypeQueryNode().ExprName) + visitForDisplayParts(node.AsTypeQueryNode().ExprName()) if len(node.TypeArguments()) > 0 { parts = append(parts, &lsproto.InlayHintLabelPart{Value: "<"}) visitDisplayPartList(node.TypeArguments(), ", ") @@ -545,14 +545,14 @@ func (s *inlayHintState) getInlayHintLabelParts(node *ast.Node, idToSymbol map[* } parts = append(parts, &lsproto.InlayHintLabelPart{Value: "}"}) case ast.KindArrayType: - visitForDisplayParts(node.AsArrayTypeNode().ElementType) + visitForDisplayParts(node.AsArrayTypeNode().ElementType()) parts = append(parts, &lsproto.InlayHintLabelPart{Value: "[]"}) case ast.KindTupleType: parts = append(parts, &lsproto.InlayHintLabelPart{Value: "["}) visitDisplayPartList(node.Elements(), ", ") parts = append(parts, &lsproto.InlayHintLabelPart{Value: "]"}) case ast.KindNamedTupleMember: - if node.AsNamedTupleMember().DotDotDotToken != nil { + if node.AsNamedTupleMember().DotDotDotToken() != nil { parts = append(parts, &lsproto.InlayHintLabelPart{Value: "..."}) } visitForDisplayParts(node.Name()) @@ -568,24 +568,24 @@ func (s *inlayHintState) getInlayHintLabelParts(node *ast.Node, idToSymbol map[* parts = append(parts, &lsproto.InlayHintLabelPart{Value: "..."}) visitForDisplayParts(node.Type()) case ast.KindUnionType: - if node.AsUnionTypeNode().Types != nil { - visitDisplayPartList(node.AsUnionTypeNode().Types.Nodes, " | ") + if node.AsUnionTypeNode().Types() != nil { + visitDisplayPartList(node.AsUnionTypeNode().Types().Nodes, " | ") } case ast.KindIntersectionType: - if node.AsIntersectionTypeNode().Types != nil { - visitDisplayPartList(node.AsIntersectionTypeNode().Types.Nodes, " & ") + if node.AsIntersectionTypeNode().Types() != nil { + visitDisplayPartList(node.AsIntersectionTypeNode().Types().Nodes, " & ") } case ast.KindConditionalType: - visitForDisplayParts(node.AsConditionalTypeNode().CheckType) + visitForDisplayParts(node.AsConditionalTypeNode().CheckType()) parts = append(parts, &lsproto.InlayHintLabelPart{Value: " extends "}) - visitForDisplayParts(node.AsConditionalTypeNode().ExtendsType) + visitForDisplayParts(node.AsConditionalTypeNode().ExtendsType()) parts = append(parts, &lsproto.InlayHintLabelPart{Value: " ? "}) - visitForDisplayParts(node.AsConditionalTypeNode().TrueType) + visitForDisplayParts(node.AsConditionalTypeNode().TrueType()) parts = append(parts, &lsproto.InlayHintLabelPart{Value: " : "}) - visitForDisplayParts(node.AsConditionalTypeNode().FalseType) + visitForDisplayParts(node.AsConditionalTypeNode().FalseType()) case ast.KindInferType: parts = append(parts, &lsproto.InlayHintLabelPart{Value: "infer "}) - visitForDisplayParts(node.AsInferTypeNode().TypeParameter) + visitForDisplayParts(node.AsInferTypeNode().TypeParameter()) case ast.KindParenthesizedType: parts = append(parts, &lsproto.InlayHintLabelPart{Value: "("}) visitForDisplayParts(node.Type()) @@ -594,25 +594,25 @@ func (s *inlayHintState) getInlayHintLabelParts(node *ast.Node, idToSymbol map[* parts = append(parts, &lsproto.InlayHintLabelPart{Value: scanner.TokenToString(node.AsTypeOperatorNode().Operator)}) visitForDisplayParts(node.Type()) case ast.KindIndexedAccessType: - visitForDisplayParts(node.AsIndexedAccessTypeNode().ObjectType) + visitForDisplayParts(node.AsIndexedAccessTypeNode().ObjectType()) parts = append(parts, &lsproto.InlayHintLabelPart{Value: "["}) - visitForDisplayParts(node.AsIndexedAccessTypeNode().IndexType) + visitForDisplayParts(node.AsIndexedAccessTypeNode().IndexType()) parts = append(parts, &lsproto.InlayHintLabelPart{Value: "]"}) case ast.KindMappedType: parts = append(parts, &lsproto.InlayHintLabelPart{Value: "{ "}) - if node.AsMappedTypeNode().ReadonlyToken != nil { - if node.AsMappedTypeNode().ReadonlyToken.Kind == ast.KindPlusToken { + if node.AsMappedTypeNode().ReadonlyToken() != nil { + if node.AsMappedTypeNode().ReadonlyToken().Kind == ast.KindPlusToken { parts = append(parts, &lsproto.InlayHintLabelPart{Value: "+"}) - } else if node.AsMappedTypeNode().ReadonlyToken.Kind == ast.KindMinusToken { + } else if node.AsMappedTypeNode().ReadonlyToken().Kind == ast.KindMinusToken { parts = append(parts, &lsproto.InlayHintLabelPart{Value: "-"}) } parts = append(parts, &lsproto.InlayHintLabelPart{Value: "readonly "}) } parts = append(parts, &lsproto.InlayHintLabelPart{Value: "["}) - visitForDisplayParts(node.AsMappedTypeNode().TypeParameter) - if node.AsMappedTypeNode().NameType != nil { + visitForDisplayParts(node.AsMappedTypeNode().TypeParameter()) + if node.AsMappedTypeNode().NameType() != nil { parts = append(parts, &lsproto.InlayHintLabelPart{Value: " as "}) - visitForDisplayParts(node.AsMappedTypeNode().NameType) + visitForDisplayParts(node.AsMappedTypeNode().NameType()) } parts = append(parts, &lsproto.InlayHintLabelPart{Value: "]"}) if node.QuestionToken() != nil { @@ -629,7 +629,7 @@ func (s *inlayHintState) getInlayHintLabelParts(node *ast.Node, idToSymbol map[* } parts = append(parts, &lsproto.InlayHintLabelPart{Value: "; }"}) case ast.KindLiteralType: - visitForDisplayParts(node.AsLiteralTypeNode().Literal) + visitForDisplayParts(node.AsLiteralTypeNode().Literal()) case ast.KindFunctionType: visitParametersAndTypeParameters(node) parts = append(parts, &lsproto.InlayHintLabelPart{Value: " => "}) @@ -639,11 +639,11 @@ func (s *inlayHintState) getInlayHintLabelParts(node *ast.Node, idToSymbol map[* parts = append(parts, &lsproto.InlayHintLabelPart{Value: "typeof "}) } parts = append(parts, &lsproto.InlayHintLabelPart{Value: "import("}) - visitForDisplayParts(node.AsImportTypeNode().Argument) + visitForDisplayParts(node.AsImportTypeNode().Argument()) parts = append(parts, &lsproto.InlayHintLabelPart{Value: ")"}) - if node.AsImportTypeNode().Qualifier != nil { + if node.AsImportTypeNode().Qualifier() != nil { parts = append(parts, &lsproto.InlayHintLabelPart{Value: "."}) - visitForDisplayParts(node.AsImportTypeNode().Qualifier) + visitForDisplayParts(node.AsImportTypeNode().Qualifier()) } if len(node.TypeArguments()) > 0 { parts = append(parts, &lsproto.InlayHintLabelPart{Value: "<"}) @@ -729,17 +729,17 @@ func (s *inlayHintState) getInlayHintLabelParts(node *ast.Node, idToSymbol map[* Value: scanner.TokenToString(node.AsPrefixUnaryExpression().Operator), }, ) - visitForDisplayParts(node.AsPrefixUnaryExpression().Operand) + visitForDisplayParts(node.AsPrefixUnaryExpression().Operand()) case ast.KindTemplateLiteralType: - visitForDisplayParts(node.AsTemplateLiteralTypeNode().Head) - for _, span := range node.AsTemplateLiteralTypeNode().TemplateSpans.Nodes { + visitForDisplayParts(node.AsTemplateLiteralTypeNode().Head()) + for _, span := range node.AsTemplateLiteralTypeNode().TemplateSpans().Nodes { visitForDisplayParts(span) } case ast.KindTemplateHead: parts = append(parts, &lsproto.InlayHintLabelPart{Value: s.getLiteralText(node)}) case ast.KindTemplateLiteralTypeSpan: visitForDisplayParts(node.Type()) - visitForDisplayParts(node.AsTemplateLiteralTypeSpan().Literal) + visitForDisplayParts(node.AsTemplateLiteralTypeSpan().Literal()) case ast.KindTemplateMiddle, ast.KindTemplateTail: parts = append(parts, &lsproto.InlayHintLabelPart{Value: s.getLiteralText(node)}) case ast.KindThisType: @@ -755,7 +755,7 @@ func (s *inlayHintState) getInlayHintLabelParts(node *ast.Node, idToSymbol map[* case ast.KindElementAccessExpression: visitForDisplayParts(node.Expression()) parts = append(parts, &lsproto.InlayHintLabelPart{Value: "["}) - visitForDisplayParts(node.AsElementAccessExpression().ArgumentExpression) + visitForDisplayParts(node.AsElementAccessExpression().ArgumentExpression()) parts = append(parts, &lsproto.InlayHintLabelPart{Value: "]"}) default: debug.FailBadSyntaxKind(node) @@ -873,9 +873,9 @@ func (s *inlayHintState) getParameterIdentifierInfoAtPosition(signature *checker debug.Assert(ast.IsIdentifier(associatedName.Name())) var isRestTupleElement bool if ast.IsNamedTupleMember(associatedName) { - isRestTupleElement = associatedName.AsNamedTupleMember().DotDotDotToken != nil + isRestTupleElement = associatedName.AsNamedTupleMember().DotDotDotToken() != nil } else { - isRestTupleElement = associatedName.AsParameterDeclaration().DotDotDotToken != nil + isRestTupleElement = associatedName.AsParameterDeclaration().DotDotDotToken() != nil } return ¶meterInfo{ parameter: associatedName.Name(), diff --git a/tsc/internal/ls/jsdoc.go b/tsc/internal/ls/jsdoc.go index 3e7aadf363999..0d91c7755e888 100644 --- a/tsc/internal/ls/jsdoc.go +++ b/tsc/internal/ls/jsdoc.go @@ -90,8 +90,8 @@ func declarationJSDocTags(node *ast.Node) []*ast.Node { continue } lastJSDoc := jsdocs[len(jsdocs)-1].AsJSDoc() - if lastJSDoc.Tags != nil { - return lastJSDoc.Tags.Nodes + if lastJSDoc.Tags() != nil { + return lastJSDoc.Tags().Nodes } } } @@ -110,22 +110,22 @@ func getJSDocTagText(tag *ast.Node) string { } switch tag.Kind { case ast.KindJSDocThrowsTag: - if te := tag.AsJSDocThrowsTag().TypeExpression; te != nil { + if te := tag.AsJSDocThrowsTag().TypeExpression(); te != nil { return addComment(scanner.GetTextOfNode(te)) } return comment case ast.KindJSDocImplementsTag: - return addComment(scanner.GetTextOfNode(tag.AsJSDocImplementsTag().ClassName)) + return addComment(scanner.GetTextOfNode(tag.AsJSDocImplementsTag().ClassName())) case ast.KindJSDocAugmentsTag: - return addComment(scanner.GetTextOfNode(tag.AsJSDocAugmentsTag().ClassName)) + return addComment(scanner.GetTextOfNode(tag.AsJSDocAugmentsTag().ClassName())) case ast.KindJSDocTemplateTag: templateTag := tag.AsJSDocTemplateTag() var b strings.Builder - if templateTag.Constraint != nil { - b.WriteString(scanner.GetTextOfNode(templateTag.Constraint)) + if templateTag.Constraint() != nil { + b.WriteString(scanner.GetTextOfNode(templateTag.Constraint())) } - if templateTag.TypeParameters != nil { - for i, tp := range templateTag.TypeParameters.Nodes { + if templateTag.TypeParameters() != nil { + for i, tp := range templateTag.TypeParameters().Nodes { if i == 0 && b.Len() != 0 { b.WriteString(" ") } @@ -143,11 +143,11 @@ func getJSDocTagText(tag *ast.Node) string { } return b.String() case ast.KindJSDocTypeTag: - return addComment(scanner.GetTextOfNode(tag.AsJSDocTypeTag().TypeExpression)) + return addComment(scanner.GetTextOfNode(tag.AsJSDocTypeTag().TypeExpression())) case ast.KindJSDocSatisfiesTag: - return addComment(scanner.GetTextOfNode(tag.AsJSDocSatisfiesTag().TypeExpression)) + return addComment(scanner.GetTextOfNode(tag.AsJSDocSatisfiesTag().TypeExpression())) case ast.KindJSDocSeeTag: - if ne := tag.AsJSDocSeeTag().NameExpression; ne != nil { + if ne := tag.AsJSDocSeeTag().NameExpression(); ne != nil { return addComment(scanner.GetTextOfNode(ne)) } return comment @@ -179,17 +179,17 @@ func getJSDocOrTag(c *checker.Checker, node *ast.Node, seenSymbols *collections. // For binding patterns, match JSDoc @param tags by position rather than by name return getJSDocParameterTagByPosition(c, node) } - return getMatchingJSDocTag(c, node.Parent, name.Text(), isMatchingParameterTag, seenSymbols) + return getMatchingJSDocTag(c, node.Parent(), name.Text(), isMatchingParameterTag, seenSymbols) case ast.IsTypeParameterDeclaration(node): - return getMatchingJSDocTag(c, node.Parent, node.Name().Text(), isMatchingTemplateTag, seenSymbols) - case ast.IsVariableDeclaration(node) && ast.IsVariableDeclarationList(node.Parent) && core.FirstOrNil(node.Parent.AsVariableDeclarationList().Declarations.Nodes) == node: - return getJSDocOrTag(c, node.Parent.Parent, seenSymbols) + return getMatchingJSDocTag(c, node.Parent(), node.Name().Text(), isMatchingTemplateTag, seenSymbols) + case ast.IsVariableDeclaration(node) && ast.IsVariableDeclarationList(node.Parent()) && core.FirstOrNil(node.Parent().AsVariableDeclarationList().Declarations().Nodes) == node: + return getJSDocOrTag(c, node.Parent().Parent(), seenSymbols) case (ast.IsFunctionExpressionOrArrowFunction(node) || ast.IsClassExpression(node)) && - (ast.IsVariableDeclaration(node.Parent) || ast.IsPropertyDeclaration(node.Parent) || ast.IsPropertyAssignment(node.Parent)) && node.Parent.Initializer() == node: - return getJSDocOrTag(c, node.Parent, seenSymbols) - case ast.IsBindingElement(node) && ast.IsObjectBindingPattern(node.Parent): + (ast.IsVariableDeclaration(node.Parent()) || ast.IsPropertyDeclaration(node.Parent()) || ast.IsPropertyAssignment(node.Parent())) && node.Parent().Initializer() == node: + return getJSDocOrTag(c, node.Parent(), seenSymbols) + case ast.IsBindingElement(node) && ast.IsObjectBindingPattern(node.Parent()): if name := node.PropertyNameOrName(); ast.IsIdentifier(name) { - if objectType := c.GetTypeAtLocation(node.Parent); objectType != nil { + if objectType := c.GetTypeAtLocation(node.Parent()); objectType != nil { if prop := c.GetPropertyOfType(objectType, name.Text()); prop != nil { for _, d := range prop.Declarations { if jsdoc := getJSDoc(d); jsdoc != nil { @@ -200,7 +200,7 @@ func getJSDocOrTag(c *checker.Checker, node *ast.Node, seenSymbols *collections. } } } - if symbol := node.Symbol(); symbol != nil && node.Parent != nil { + if symbol := node.Symbol(); symbol != nil && node.Parent() != nil { if ast.IsFunctionDeclaration(node) || ast.IsMethodDeclaration(node) || ast.IsMethodSignatureDeclaration(node) || ast.IsConstructorDeclaration(node) || ast.IsConstructSignatureDeclaration(node) { firstSignature := core.Find(symbol.Declarations, ast.IsFunctionLike) if firstSignature != nil && node != firstSignature { @@ -209,9 +209,9 @@ func getJSDocOrTag(c *checker.Checker, node *ast.Node, seenSymbols *collections. } } } - if ast.IsClassOrInterfaceLike(node.Parent) { + if ast.IsClassOrInterfaceLike(node.Parent()) { isStatic := ast.HasStaticModifier(node) - classType := c.GetDeclaredTypeOfSymbol(node.Parent.Symbol()) + classType := c.GetDeclaredTypeOfSymbol(node.Parent().Symbol()) if isStatic { // For static members, use the checker's base constructor type resolution. // This correctly handles intersection constructor types from mixins @@ -238,7 +238,7 @@ func getJSDocOrTag(c *checker.Checker, node *ast.Node, seenSymbols *collections. func getMatchingJSDocTag(c *checker.Checker, node *ast.Node, name string, match func(*ast.Node, string) bool, seenSymbols *collections.Set[*ast.Symbol]) *ast.Node { if jsdoc := getJSDocOrTag(c, node, seenSymbols); jsdoc != nil && jsdoc.Kind == ast.KindJSDoc { - if tags := jsdoc.AsJSDoc().Tags; tags != nil { + if tags := jsdoc.AsJSDoc().Tags(); tags != nil { for _, tag := range tags.Nodes { if match(tag, name) { return tag @@ -252,7 +252,7 @@ func getMatchingJSDocTag(c *checker.Checker, node *ast.Node, name string, match // getJSDocParameterTagByPosition finds a JSDoc @param tag for a binding pattern parameter by position. // Since binding patterns don't have a simple name, we match the @param tag at the same index as the parameter. func getJSDocParameterTagByPosition(c *checker.Checker, param *ast.Node) *ast.Node { - parent := param.Parent + parent := param.Parent() if parent == nil { return nil } @@ -277,7 +277,7 @@ func getJSDocParameterTagByPosition(c *checker.Checker, param *ast.Node) *ast.No } // Collect all @param tags in order - tags := jsdoc.AsJSDoc().Tags + tags := jsdoc.AsJSDoc().Tags() if tags == nil { return nil } diff --git a/tsc/internal/ls/jsdoc_snippet.go b/tsc/internal/ls/jsdoc_snippet.go index a436e085bfd56..9ee3f355c4c7d 100644 --- a/tsc/internal/ls/jsdoc_snippet.go +++ b/tsc/internal/ls/jsdoc_snippet.go @@ -206,7 +206,7 @@ func skipWhitespace(text string, position int) int { } func getCommentOwnerInfo(tokenAtPos *ast.Node, generateReturnInDocTemplate bool) *commentOwnerInfo { - for node := tokenAtPos; node != nil; node = node.Parent { + for node := tokenAtPos; node != nil; node = node.Parent() { info, quit := getCommentOwnerInfoWorker(node, generateReturnInDocTemplate) if info != nil || quit { return info @@ -223,18 +223,18 @@ func getCommentOwnerInfoWorker(commentOwner *ast.Node, generateReturnInDocTempla case ast.KindFunctionDeclaration, ast.KindFunctionExpression, ast.KindMethodDeclaration, ast.KindConstructor, ast.KindMethodSignature, ast.KindArrowFunction: return &commentOwnerInfo{commentOwner: commentOwner, parameters: commentOwner.Parameters(), hasReturn: hasReturn(commentOwner, generateReturnInDocTemplate)}, false case ast.KindPropertyAssignment: - return getCommentOwnerInfoWorker(commentOwner.AsPropertyAssignment().Initializer, generateReturnInDocTemplate) + return getCommentOwnerInfoWorker(commentOwner.AsPropertyAssignment().Initializer(), generateReturnInDocTemplate) case ast.KindClassDeclaration, ast.KindInterfaceDeclaration, ast.KindEnumDeclaration, ast.KindEnumMember, ast.KindTypeAliasDeclaration: return &commentOwnerInfo{commentOwner: commentOwner}, false case ast.KindPropertySignature: - if typeNode := commentOwner.AsPropertySignatureDeclaration().Type; typeNode != nil && ast.IsFunctionTypeNode(typeNode) { + if typeNode := commentOwner.AsPropertySignatureDeclaration().Type(); typeNode != nil && ast.IsFunctionTypeNode(typeNode) { return &commentOwnerInfo{commentOwner: commentOwner, parameters: typeNode.Parameters(), hasReturn: hasReturn(typeNode, generateReturnInDocTemplate)}, false } return &commentOwnerInfo{commentOwner: commentOwner}, false case ast.KindVariableStatement: - declarations := commentOwner.AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes + declarations := commentOwner.AsVariableStatement().DeclarationList().AsVariableDeclarationList().Declarations().Nodes if len(declarations) == 1 { - if initializer := declarations[0].AsVariableDeclaration().Initializer; initializer != nil { + if initializer := declarations[0].AsVariableDeclaration().Initializer(); initializer != nil { if host := getRightHandSideOfAssignment(initializer); host != nil { return &commentOwnerInfo{commentOwner: commentOwner, parameters: host.Parameters(), hasReturn: hasReturn(host, generateReturnInDocTemplate)}, false } @@ -244,23 +244,23 @@ func getCommentOwnerInfoWorker(commentOwner *ast.Node, generateReturnInDocTempla case ast.KindSourceFile: return nil, true case ast.KindModuleDeclaration: - if commentOwner.Parent.Kind == ast.KindModuleDeclaration { + if commentOwner.Parent().Kind == ast.KindModuleDeclaration { return nil, false } return &commentOwnerInfo{commentOwner: commentOwner}, false case ast.KindExpressionStatement: - return getCommentOwnerInfoWorker(commentOwner.AsExpressionStatement().Expression, generateReturnInDocTemplate) + return getCommentOwnerInfoWorker(commentOwner.AsExpressionStatement().Expression(), generateReturnInDocTemplate) case ast.KindBinaryExpression: binaryExpression := commentOwner.AsBinaryExpression() if ast.GetAssignmentDeclarationKind(commentOwner) == ast.JSDeclarationKindNone { return nil, true } - if ast.IsFunctionLike(binaryExpression.Right) { - return &commentOwnerInfo{commentOwner: commentOwner, parameters: binaryExpression.Right.Parameters(), hasReturn: hasReturn(binaryExpression.Right, generateReturnInDocTemplate)}, false + if ast.IsFunctionLike(binaryExpression.Right()) { + return &commentOwnerInfo{commentOwner: commentOwner, parameters: binaryExpression.Right().Parameters(), hasReturn: hasReturn(binaryExpression.Right(), generateReturnInDocTemplate)}, false } return &commentOwnerInfo{commentOwner: commentOwner}, false case ast.KindPropertyDeclaration: - if initializer := commentOwner.AsPropertyDeclaration().Initializer; initializer != nil && ast.IsFunctionExpressionOrArrowFunction(initializer) { + if initializer := commentOwner.AsPropertyDeclaration().Initializer(); initializer != nil && ast.IsFunctionExpressionOrArrowFunction(initializer) { return &commentOwnerInfo{commentOwner: commentOwner, parameters: initializer.Parameters(), hasReturn: hasReturn(initializer, generateReturnInDocTemplate)}, false } } @@ -289,7 +289,7 @@ func getRightHandSideOfAssignment(rightHandSide *ast.Node) *ast.Node { return nil } for rightHandSide.Kind == ast.KindParenthesizedExpression { - rightHandSide = rightHandSide.AsParenthesizedExpression().Expression + rightHandSide = rightHandSide.AsParenthesizedExpression().Expression() } switch rightHandSide.Kind { case ast.KindFunctionExpression, ast.KindArrowFunction: @@ -310,7 +310,7 @@ func parameterDocComments(parameters []*ast.ParameterDeclarationNode, isJavaScri } paramType := "" if isJavaScriptFile { - if parameter.AsParameterDeclaration().DotDotDotToken != nil { + if parameter.AsParameterDeclaration().DotDotDotToken() != nil { paramType = "{...any} " } else { paramType = "{any} " @@ -351,7 +351,7 @@ func isNonEmptyJSDoc(jsdoc *ast.Node) bool { return false } data := jsdoc.AsJSDoc() - return data.Comment != nil && len(data.Comment.Nodes) > 0 || data.Tags != nil && len(data.Tags.Nodes) > 0 + return data.Comment() != nil && len(data.Comment().Nodes) > 0 || data.Tags() != nil && len(data.Tags().Nodes) > 0 } func hasJSDocTags(node *ast.Node, file *ast.SourceFile) bool { @@ -359,7 +359,7 @@ func hasJSDocTags(node *ast.Node, file *ast.SourceFile) bool { if len(jsdocs) == 0 { return false } - tags := jsdocs[len(jsdocs)-1].AsJSDoc().Tags + tags := jsdocs[len(jsdocs)-1].AsJSDoc().Tags() return tags != nil && len(tags.Nodes) > 0 } diff --git a/tsc/internal/ls/linkedediting.go b/tsc/internal/ls/linkedediting.go index 4aba5d388f862..0659980e2af25 100644 --- a/tsc/internal/ls/linkedediting.go +++ b/tsc/internal/ls/linkedediting.go @@ -25,14 +25,14 @@ func (l *LanguageService) ProvideLinkedEditingRange(ctx context.Context, params position := positions[0].Position token := astnav.FindPrecedingToken(sourceFile, int(position)) - if token == nil || token.Parent.Kind == ast.KindSourceFile { + if token == nil || token.Parent().Kind == ast.KindSourceFile { return lsproto.LinkedEditingRangeResponse{}, nil } - if ast.IsJsxFragment(token.Parent.Parent) { - fragment := token.Parent.Parent.AsJsxFragment() - openFragment := fragment.OpeningFragment - closeFragment := fragment.ClosingFragment + if ast.IsJsxFragment(token.Parent().Parent()) { + fragment := token.Parent().Parent().AsJsxFragment() + openFragment := fragment.OpeningFragment() + closeFragment := fragment.ClosingFragment() if openFragment.Flags&ast.NodeFlagsThisNodeOrAnySubNodesHasError != 0 || closeFragment.Flags&ast.NodeFlagsThisNodeOrAnySubNodesHasError != 0 { return lsproto.LinkedEditingRangeResponse{}, nil } @@ -61,7 +61,7 @@ func (l *LanguageService) ProvideLinkedEditingRange(ctx context.Context, params }, nil } else { // determines if the cursor is in an element tag - tag := ast.FindAncestor(token.Parent, func(n *ast.Node) bool { + tag := ast.FindAncestor(token.Parent(), func(n *ast.Node) bool { if ast.IsJsxOpeningElement(n) || ast.IsJsxClosingElement(n) { return true } @@ -72,9 +72,9 @@ func (l *LanguageService) ProvideLinkedEditingRange(ctx context.Context, params } debug.Assert(ast.IsJsxOpeningElement(tag) || ast.IsJsxClosingElement(tag), "tag should be opening or closing element") - jsxElement := tag.Parent.AsJsxElement() - openTag := jsxElement.OpeningElement - closeTag := jsxElement.ClosingElement + jsxElement := tag.Parent().AsJsxElement() + openTag := jsxElement.OpeningElement() + closeTag := jsxElement.ClosingElement() openTagNameStart := astnav.GetStartOfNode(openTag.TagName().AsNode(), sourceFile, false) openTagNameEnd := openTag.TagName().End() diff --git a/tsc/internal/ls/lsutil/asi.go b/tsc/internal/ls/lsutil/asi.go index e59901f9139c4..0d33528d4a90e 100644 --- a/tsc/internal/ls/lsutil/asi.go +++ b/tsc/internal/ls/lsutil/asi.go @@ -92,7 +92,7 @@ func NodeIsASICandidate(node *ast.Node, file *ast.SourceFile) bool { return true } - topNode := ast.FindAncestor(node, func(ancestor *ast.Node) bool { return ancestor.Parent == nil }) + topNode := ast.FindAncestor(node, func(ancestor *ast.Node) bool { return ancestor.Parent() == nil }) nextToken := astnav.FindNextToken(node, topNode, file) if nextToken == nil || nextToken.Kind == ast.KindCloseBraceToken { return true diff --git a/tsc/internal/ls/lsutil/completednode.go b/tsc/internal/ls/lsutil/completednode.go index e54bad67f449c..467c504de816a 100644 --- a/tsc/internal/ls/lsutil/completednode.go +++ b/tsc/internal/ls/lsutil/completednode.go @@ -36,7 +36,7 @@ func IsCompletedNode(n *ast.Node, sourceFile *ast.SourceFile) bool { return nodeEndsWith(n, ast.KindCloseBraceToken, sourceFile) case ast.KindCatchClause: - return IsCompletedNode(n.AsCatchClause().Block, sourceFile) + return IsCompletedNode(n.AsCatchClause().Block(), sourceFile) case ast.KindNewExpression: if n.ArgumentList() == nil { @@ -77,10 +77,10 @@ func IsCompletedNode(n *ast.Node, sourceFile *ast.SourceFile) bool { return n.Body() != nil && IsCompletedNode(n.Body(), sourceFile) case ast.KindIfStatement: - if n.AsIfStatement().ElseStatement != nil { - return IsCompletedNode(n.AsIfStatement().ElseStatement, sourceFile) + if n.AsIfStatement().ElseStatement() != nil { + return IsCompletedNode(n.AsIfStatement().ElseStatement(), sourceFile) } - return IsCompletedNode(n.AsIfStatement().ThenStatement, sourceFile) + return IsCompletedNode(n.AsIfStatement().ThenStatement(), sourceFile) case ast.KindExpressionStatement: return IsCompletedNode(n.Expression(), sourceFile) || @@ -94,8 +94,8 @@ func IsCompletedNode(n *ast.Node, sourceFile *ast.SourceFile) bool { return nodeEndsWith(n, ast.KindCloseBracketToken, sourceFile) case ast.KindIndexSignature: - if n.AsIndexSignatureDeclaration().Type != nil { - return IsCompletedNode(n.AsIndexSignatureDeclaration().Type, sourceFile) + if n.AsIndexSignatureDeclaration().Type() != nil { + return IsCompletedNode(n.AsIndexSignatureDeclaration().Type(), sourceFile) } return hasChildOfKind(n, ast.KindCloseBracketToken, sourceFile) @@ -117,7 +117,7 @@ func IsCompletedNode(n *ast.Node, sourceFile *ast.SourceFile) bool { return IsCompletedNode(n.Statement(), sourceFile) case ast.KindTypeQuery: - return IsCompletedNode(n.AsTypeQueryNode().ExprName, sourceFile) + return IsCompletedNode(n.AsTypeQueryNode().ExprName(), sourceFile) case ast.KindTypeOfExpression, ast.KindDeleteExpression, @@ -127,30 +127,30 @@ func IsCompletedNode(n *ast.Node, sourceFile *ast.SourceFile) bool { return IsCompletedNode(n.Expression(), sourceFile) case ast.KindTaggedTemplateExpression: - return IsCompletedNode(n.AsTaggedTemplateExpression().Template, sourceFile) + return IsCompletedNode(n.AsTaggedTemplateExpression().Template(), sourceFile) case ast.KindTemplateExpression: - if n.AsTemplateExpression().TemplateSpans == nil { + if n.AsTemplateExpression().TemplateSpans() == nil { return false } - lastSpan := core.LastOrNil(n.AsTemplateExpression().TemplateSpans.Nodes) + lastSpan := core.LastOrNil(n.AsTemplateExpression().TemplateSpans().Nodes) return IsCompletedNode(lastSpan, sourceFile) case ast.KindTemplateSpan: - return ast.NodeIsPresent(n.AsTemplateSpan().Literal) + return ast.NodeIsPresent(n.AsTemplateSpan().Literal()) case ast.KindExportDeclaration, ast.KindImportDeclaration: return ast.NodeIsPresent(n.ModuleSpecifier()) case ast.KindPrefixUnaryExpression: - return IsCompletedNode(n.AsPrefixUnaryExpression().Operand, sourceFile) + return IsCompletedNode(n.AsPrefixUnaryExpression().Operand(), sourceFile) case ast.KindBinaryExpression: - return IsCompletedNode(n.AsBinaryExpression().Right, sourceFile) + return IsCompletedNode(n.AsBinaryExpression().Right(), sourceFile) case ast.KindConditionalExpression: - return IsCompletedNode(n.AsConditionalExpression().WhenFalse, sourceFile) + return IsCompletedNode(n.AsConditionalExpression().WhenFalse(), sourceFile) default: return true diff --git a/tsc/internal/ls/lsutil/organizeimports.go b/tsc/internal/ls/lsutil/organizeimports.go index 655cd800c8f53..1e4c86f42ed79 100644 --- a/tsc/internal/ls/lsutil/organizeimports.go +++ b/tsc/internal/ls/lsutil/organizeimports.go @@ -272,20 +272,20 @@ func getModuleSpecifierExpression(declaration *ast.Statement) *ast.Expression { switch declaration.Kind { case ast.KindImportEqualsDeclaration: importEquals := declaration.AsImportEqualsDeclaration() - if importEquals.ModuleReference.Kind == ast.KindExternalModuleReference { - return importEquals.ModuleReference.Expression() + if importEquals.ModuleReference().Kind == ast.KindExternalModuleReference { + return importEquals.ModuleReference().Expression() } return nil case ast.KindImportDeclaration: return declaration.ModuleSpecifier() case ast.KindVariableStatement: - declarations := declaration.AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes + declarations := declaration.AsVariableStatement().DeclarationList().AsVariableDeclarationList().Declarations().Nodes if len(declarations) > 0 { initializer := declarations[0].Initializer() if initializer != nil && initializer.Kind == ast.KindCallExpression { callExpr := initializer.AsCallExpression() - if len(callExpr.Arguments.Nodes) > 0 { - return callExpr.Arguments.Nodes[0] + if len(callExpr.Arguments().Nodes) > 0 { + return callExpr.Arguments().Nodes[0] } } } @@ -343,14 +343,14 @@ func getImportKindOrder(s1 *ast.Statement) int { switch s1.Kind { case ast.KindImportDeclaration: importDecl := s1.AsImportDeclaration() - if importDecl.ImportClause == nil { + if importDecl.ImportClause() == nil { return importKindOrderSideEffect } - importClause := importDecl.ImportClause.AsImportClause() + importClause := importDecl.ImportClause().AsImportClause() if importClause.IsTypeOnly() { return importKindOrderTypeOnly } - if importClause.NamedBindings != nil && importClause.NamedBindings.Kind == ast.KindNamespaceImport { + if importClause.NamedBindings() != nil && importClause.NamedBindings().Kind == ast.KindNamespaceImport { return importKindOrderNamespace } if importClause.Name() != nil { @@ -472,22 +472,22 @@ func detectNamedImportOrganizationBySort( var importDeclsWithNamed []*ast.Statement for _, imp := range originalGroups { - if imp.AsImportDeclaration().ImportClause == nil { + if imp.AsImportDeclaration().ImportClause() == nil { continue } - clause := imp.AsImportDeclaration().ImportClause.AsImportClause() - if clause.NamedBindings == nil || clause.NamedBindings.Kind != ast.KindNamedImports { + clause := imp.AsImportDeclaration().ImportClause().AsImportClause() + if clause.NamedBindings() == nil || clause.NamedBindings().Kind != ast.KindNamedImports { continue } - namedImports := clause.NamedBindings.AsNamedImports() - if len(namedImports.Elements.Nodes) == 0 { + namedImports := clause.NamedBindings().AsNamedImports() + if len(namedImports.Elements().Nodes) == 0 { continue } if !bothNamedImports { hasTypeOnly := false hasRegular := false - for _, elem := range namedImports.Elements.Nodes { + for _, elem := range namedImports.Elements().Nodes { if elem.IsTypeOnly() { hasTypeOnly = true } else { @@ -508,9 +508,9 @@ func detectNamedImportOrganizationBySort( namedImportsByDecl := make([][]*ast.Statement, 0, len(importDeclsWithNamed)) for _, imp := range importDeclsWithNamed { - clause := imp.AsImportDeclaration().ImportClause.AsImportClause() - namedImports := clause.NamedBindings.AsNamedImports() - namedImportsByDecl = append(namedImportsByDecl, namedImports.Elements.Nodes) + clause := imp.AsImportDeclaration().ImportClause().AsImportClause() + namedImports := clause.NamedBindings().AsNamedImports() + namedImportsByDecl = append(namedImportsByDecl, namedImports.Elements().Nodes) } if !bothNamedImports || len(typesToTest) == 0 { diff --git a/tsc/internal/ls/lsutil/symbol_display.go b/tsc/internal/ls/lsutil/symbol_display.go index 0f1fee4527494..b8b910b500372 100644 --- a/tsc/internal/ls/lsutil/symbol_display.go +++ b/tsc/internal/ls/lsutil/symbol_display.go @@ -330,8 +330,8 @@ func isLocalVariableOrFunction(symbol *ast.Symbol) bool { } // If the parent is not source file or module block, it is a local variable. - parent := decl.Parent - for ; !ast.IsFunctionBlock(parent); parent = parent.Parent { + parent := decl.Parent() + for ; !ast.IsFunctionBlock(parent); parent = parent.Parent() { // Reached source file or module block if parent.Kind == ast.KindSourceFile || parent.Kind == ast.KindModuleBlock { break diff --git a/tsc/internal/ls/lsutil/utilities.go b/tsc/internal/ls/lsutil/utilities.go index 69c50f1cc9dd5..035eb15e08b2d 100644 --- a/tsc/internal/ls/lsutil/utilities.go +++ b/tsc/internal/ls/lsutil/utilities.go @@ -104,7 +104,7 @@ func GetQuotePreference(sourceFile *ast.SourceFile, preferences UserPreferences) } // ignore synthetic import added when importHelpers: true firstModuleSpecifier := core.Find(sourceFile.Imports(), func(n *ast.Node) bool { - return ast.IsStringLiteral(n) && !ast.NodeIsSynthesized(n.Parent) + return ast.IsStringLiteral(n) && !ast.NodeIsSynthesized(n.Parent()) }) if firstModuleSpecifier != nil { return QuotePreferenceFromString(firstModuleSpecifier.AsStringLiteral()) diff --git a/tsc/internal/ls/organizeimports.go b/tsc/internal/ls/organizeimports.go index d7a8390f2b607..38bcf7a803485 100644 --- a/tsc/internal/ls/organizeimports.go +++ b/tsc/internal/ls/organizeimports.go @@ -88,13 +88,13 @@ func (l *LanguageService) OrganizeImports( } ambientModule := stmt.AsModuleDeclaration() - if ambientModule.Body == nil { + if ambientModule.Body() == nil { continue } - moduleBody := ambientModule.Body.AsModuleBlock() + moduleBody := ambientModule.Body().AsModuleBlock() - ambientModuleImportDecls := lsutil.FilterImportDeclarations(moduleBody.Statements.Nodes) + ambientModuleImportDecls := lsutil.FilterImportDeclarations(moduleBody.Statements().Nodes) ambientModuleImportGroupDecls := groupByNewlineContiguous(sourceFile, ambientModuleImportDecls) for _, importGroupDecl := range ambientModuleImportGroupDecls { @@ -103,7 +103,7 @@ func (l *LanguageService) OrganizeImports( if kind != lsproto.CodeActionKindSourceRemoveUnusedImportsTs { var ambientModuleExportDecls []*ast.Statement - for _, s := range moduleBody.Statements.Nodes { + for _, s := range moduleBody.Statements().Nodes { if s.Kind == ast.KindExportDeclaration { ambientModuleExportDecls = append(ambientModuleExportDecls, s) } @@ -246,7 +246,7 @@ func removeUnusedImports(oldImports []*ast.Statement, sourceFile *ast.SourceFile usedImports := make([]*ast.Statement, 0, len(oldImports)) for _, importDecl := range oldImports { - importClause := importDecl.AsImportDeclaration().ImportClause + importClause := importDecl.AsImportDeclaration().ImportClause() if importClause == nil { usedImports = append(usedImports, importDecl) continue @@ -254,7 +254,7 @@ func removeUnusedImports(oldImports []*ast.Statement, sourceFile *ast.SourceFile clause := importClause.AsImportClause() name := clause.Name() - namedBindings := clause.NamedBindings + namedBindings := clause.NamedBindings() if name != nil && !typeChecker.IsDeclarationUsed(sourceFile, name.AsIdentifier(), jsxElementsPresent, jsxModeNeedsExplicitImport) { name = nil @@ -270,10 +270,10 @@ func removeUnusedImports(oldImports []*ast.Statement, sourceFile *ast.SourceFile case ast.KindNamedImports: namedImports := namedBindings.AsNamedImports() originalBindings := namedBindings - newElements := filterUsedImportSpecifiers(namedImports.Elements.Nodes, typeChecker, sourceFile, jsxElementsPresent, jsxModeNeedsExplicitImport) + newElements := filterUsedImportSpecifiers(namedImports.Elements().Nodes, typeChecker, sourceFile, jsxElementsPresent, jsxModeNeedsExplicitImport) if len(newElements) == 0 { namedBindings = nil - } else if len(newElements) < len(namedImports.Elements.Nodes) { + } else if len(newElements) < len(namedImports.Elements().Nodes) { newList := factory.NewNodeList(newElements) updatedNamedImports := factory.UpdateNamedImports(namedImports, newList) namedBindings = updatedNamedImports.AsNode() @@ -291,8 +291,8 @@ func removeUnusedImports(oldImports []*ast.Statement, sourceFile *ast.SourceFile importDeclNode, importDeclNode.Modifiers(), newClause.AsNode(), - importDeclNode.ModuleSpecifier, - importDeclNode.Attributes, + importDeclNode.ModuleSpecifier(), + importDeclNode.Attributes(), ) usedImports = append(usedImports, newImportDecl) } else { @@ -304,8 +304,8 @@ func removeUnusedImports(oldImports []*ast.Statement, sourceFile *ast.SourceFile importDeclNode, importDeclNode.Modifiers(), nil, // no import clause - importDeclNode.ModuleSpecifier, - importDeclNode.Attributes, + importDeclNode.ModuleSpecifier(), + importDeclNode.Attributes(), ) usedImports = append(usedImports, newImportDecl) } else { @@ -361,8 +361,8 @@ func getImportAttributesKey(attributes *ast.ImportAttributesNode) string { key.WriteString(importAttrs.Token.String()) key.WriteString(" ") - attrNodes := make([]*ast.Node, len(importAttrs.Attributes.Nodes)) - copy(attrNodes, importAttrs.Attributes.Nodes) + attrNodes := make([]*ast.Node, len(importAttrs.Attributes().Nodes)) + copy(attrNodes, importAttrs.Attributes().Nodes) slices.SortFunc(attrNodes, func(a, b *ast.Node) int { aName := a.AsImportAttribute().Name().Text() bName := b.AsImportAttribute().Name().Text() @@ -373,12 +373,12 @@ func getImportAttributesKey(attributes *ast.ImportAttributesNode) string { attr := attrNode.AsImportAttribute() key.WriteString(attr.Name().Text()) key.WriteString(":") - if ast.IsStringLiteralLike(attr.Value.AsNode()) { + if ast.IsStringLiteralLike(attr.Value().AsNode()) { key.WriteString(`"`) - key.WriteString(attr.Value.Text()) + key.WriteString(attr.Value().Text()) key.WriteString(`"`) } else { - key.WriteString(attr.Value.AsNode().Text()) + key.WriteString(attr.Value().AsNode().Text()) } key.WriteString(" ") } @@ -458,7 +458,7 @@ func coalesceImportsWorker( var attributeKeys []string for _, importDecl := range importDecls { - key := getImportAttributesKey(importDecl.AsImportDeclaration().Attributes) + key := getImportAttributesKey(importDecl.AsImportDeclaration().Attributes()) if _, exists := importGroupsByAttributes[key]; !exists { attributeKeys = append(attributeKeys, key) } @@ -475,8 +475,8 @@ func coalesceImportsWorker( coalescedImports = append(coalescedImports, categorized.importWithoutClause) } slices.SortStableFunc(categorized.sourcePhaseImports, func(a, b *ast.Statement) int { - a = a.AsImportDeclaration().ImportClause - b = b.AsImportDeclaration().ImportClause + a = a.AsImportDeclaration().ImportClause() + b = b.AsImportDeclaration().ImportClause() if a.Name() == nil && b.Name() == nil { return 0 } @@ -503,8 +503,8 @@ func coalesceImportsWorker( defaultImport := group.defaultImports[0] namespaceImport := group.namespaceImports[0] - defaultClause := defaultImport.AsImportDeclaration().ImportClause.AsImportClause() - namespaceBindings := namespaceImport.AsImportDeclaration().ImportClause.AsImportClause().NamedBindings + defaultClause := defaultImport.AsImportDeclaration().ImportClause().AsImportClause() + namespaceBindings := namespaceImport.AsImportDeclaration().ImportClause().AsImportClause().NamedBindings() newClause := factory.UpdateImportClause(defaultClause, defaultClause.PhaseModifier, defaultClause.Name(), namespaceBindings) defaultDeclNode := defaultImport.AsImportDeclaration() @@ -512,29 +512,29 @@ func coalesceImportsWorker( defaultDeclNode, defaultDeclNode.Modifiers(), newClause, - defaultDeclNode.ModuleSpecifier, - defaultDeclNode.Attributes, + defaultDeclNode.ModuleSpecifier(), + defaultDeclNode.Attributes(), ) coalescedImports = append(coalescedImports, newImportDecl) continue } slices.SortFunc(group.namespaceImports, func(a, b *ast.Statement) int { - n1 := a.AsImportDeclaration().ImportClause.AsImportClause().NamedBindings.AsNamespaceImport().Name() - n2 := b.AsImportDeclaration().ImportClause.AsImportClause().NamedBindings.AsNamespaceImport().Name() + n1 := a.AsImportDeclaration().ImportClause().AsImportClause().NamedBindings().AsNamespaceImport().Name() + n2 := b.AsImportDeclaration().ImportClause().AsImportClause().NamedBindings().AsNamespaceImport().Name() return comparer(n1.Text(), n2.Text()) }) for _, nsImport := range group.namespaceImports { nsImportDecl := nsImport.AsImportDeclaration() - clause := nsImportDecl.ImportClause.AsImportClause() - newClause := factory.UpdateImportClause(clause, clause.PhaseModifier, nil, clause.NamedBindings) + clause := nsImportDecl.ImportClause().AsImportClause() + newClause := factory.UpdateImportClause(clause, clause.PhaseModifier, nil, clause.NamedBindings()) newImportDecl := factory.UpdateImportDeclaration( nsImportDecl, nsImportDecl.Modifiers(), newClause, - nsImportDecl.ModuleSpecifier, - nsImportDecl.Attributes, + nsImportDecl.ModuleSpecifier(), + nsImportDecl.Attributes(), ) coalescedImports = append(coalescedImports, newImportDecl) } @@ -561,10 +561,10 @@ func coalesceImportsWorker( var newImportSpecifiers []*ast.Node if len(group.defaultImports) == 1 { - newDefaultImport = group.defaultImports[0].AsImportDeclaration().ImportClause.AsImportClause().Name() + newDefaultImport = group.defaultImports[0].AsImportDeclaration().ImportClause().AsImportClause().Name() } else { for _, defaultImport := range group.defaultImports { - defaultClause := defaultImport.AsImportDeclaration().ImportClause.AsImportClause() + defaultClause := defaultImport.AsImportDeclaration().ImportClause().AsImportClause() defaultName := defaultClause.Name() propertyName := factory.NewIdentifier("default") importSpec := factory.NewImportSpecifier(false, propertyName, defaultName) @@ -585,8 +585,8 @@ func coalesceImportsWorker( } else { sortedList := factory.NewNodeList(newImportSpecifiers) if firstNamedImport != nil { - firstNamedBindings := firstNamedImport.AsImportDeclaration().ImportClause.AsImportClause().NamedBindings.AsNamedImports() - originalElements := firstNamedBindings.Elements + firstNamedBindings := firstNamedImport.AsImportDeclaration().ImportClause().AsImportClause().NamedBindings().AsNamedImports() + originalElements := firstNamedBindings.Elements() if originalElements.HasTrailingComma() { sortedList.Loc = originalElements.Loc } @@ -597,7 +597,7 @@ func coalesceImportsWorker( } if sourceFile != nil && newNamedImports != nil && firstNamedImport != nil { - firstNamedBindings := firstNamedImport.AsImportDeclaration().ImportClause.AsImportClause().NamedBindings + firstNamedBindings := firstNamedImport.AsImportDeclaration().ImportClause().AsImportClause().NamedBindings() if !ast.NodeIsSynthesized(firstNamedBindings.AsNode()) && !printer.RangeIsOnSingleLine(firstNamedBindings.Loc, sourceFile) { changeTracker.SetEmitFlags(newNamedImports.AsNode(), printer.EFMultiLine) } @@ -606,13 +606,13 @@ func coalesceImportsWorker( if isTypeOnly && newDefaultImport != nil && newNamedImports != nil { importDeclNode := importDecl.AsImportDeclaration() - defaultClause := factory.NewImportClause(importDeclNode.ImportClause.AsImportClause().PhaseModifier, newDefaultImport, nil) + defaultClause := factory.NewImportClause(importDeclNode.ImportClause().AsImportClause().PhaseModifier, newDefaultImport, nil) defaultImportDecl := factory.UpdateImportDeclaration( importDeclNode, importDeclNode.Modifiers(), defaultClause, - importDeclNode.ModuleSpecifier, - importDeclNode.Attributes, + importDeclNode.ModuleSpecifier(), + importDeclNode.Attributes(), ) coalescedImports = append(coalescedImports, defaultImportDecl) @@ -621,25 +621,25 @@ func coalesceImportsWorker( namedDeclNode = importDecl } namedImportDeclNode := namedDeclNode.AsImportDeclaration() - namedClause := factory.NewImportClause(namedImportDeclNode.ImportClause.AsImportClause().PhaseModifier, nil, newNamedImports) + namedClause := factory.NewImportClause(namedImportDeclNode.ImportClause().AsImportClause().PhaseModifier, nil, newNamedImports) namedImportDecl := factory.UpdateImportDeclaration( namedImportDeclNode, namedImportDeclNode.Modifiers(), namedClause, - namedImportDeclNode.ModuleSpecifier, - namedImportDeclNode.Attributes, + namedImportDeclNode.ModuleSpecifier(), + namedImportDeclNode.Attributes(), ) coalescedImports = append(coalescedImports, namedImportDecl) } else { importDeclNode := importDecl.AsImportDeclaration() - clauseNode := importDeclNode.ImportClause.AsImportClause() + clauseNode := importDeclNode.ImportClause().AsImportClause() newClause := factory.UpdateImportClause(clauseNode, clauseNode.PhaseModifier, newDefaultImport, newNamedImports) newImportDecl := factory.UpdateImportDeclaration( importDeclNode, importDeclNode.Modifiers(), newClause, - importDeclNode.ModuleSpecifier, - importDeclNode.Attributes, + importDeclNode.ModuleSpecifier(), + importDeclNode.Attributes(), ) coalescedImports = append(coalescedImports, newImportDecl) } @@ -671,14 +671,14 @@ func getCategorizedImports(importDecls []*ast.Statement) categorizedImports { var typeOnlyImports, regularImports importGroup for _, importDecl := range importDecls { - if importDecl.AsImportDeclaration().ImportClause == nil { + if importDecl.AsImportDeclaration().ImportClause() == nil { if importWithoutClause == nil { importWithoutClause = importDecl } continue } - clause := importDecl.AsImportDeclaration().ImportClause.AsImportClause() + clause := importDecl.AsImportDeclaration().ImportClause().AsImportClause() if clause.PhaseModifier == ast.KindSourceKeyword { sourcePhaseImports = append(sourcePhaseImports, importDecl) continue @@ -689,7 +689,7 @@ func getCategorizedImports(importDecls []*ast.Statement) categorizedImports { } name := clause.Name() - namedBindings := clause.NamedBindings + namedBindings := clause.NamedBindings() if name != nil { group.defaultImports = append(group.defaultImports, importDecl) @@ -725,8 +725,8 @@ func getNewImportSpecifiers(namedImports []*ast.Statement, factory *ast.NodeFact for _, elem := range elements { spec := elem.AsImportSpecifier() - if spec.PropertyName != nil && spec.Name() != nil { - propertyText := spec.PropertyName.Text() + if spec.PropertyName() != nil && spec.Name() != nil { + propertyText := spec.PropertyName().Text() nameText := spec.Name().Text() if propertyText == nameText { @@ -749,16 +749,16 @@ func tryGetNamedBindingElements(namedImport *ast.Statement) []*ast.Statement { } importDecl := namedImport.AsImportDeclaration() - if importDecl.ImportClause == nil { + if importDecl.ImportClause() == nil { return nil } - clause := importDecl.ImportClause.AsImportClause() - namedBindings := clause.NamedBindings + clause := importDecl.ImportClause().AsImportClause() + namedBindings := clause.NamedBindings() if namedBindings != nil && namedBindings.Kind == ast.KindNamedImports { namedImportsNode := namedBindings.AsNamedImports() - return namedImportsNode.Elements.Nodes + return namedImportsNode.Elements().Nodes } return nil @@ -777,7 +777,7 @@ func getTopLevelExportGroups(sourceFile *ast.SourceFile) [][]*ast.Statement { topLevelExportGroups = append(topLevelExportGroups, []*ast.Statement{}) } exportDecl := statements[i].AsExportDeclaration() - if exportDecl.ModuleSpecifier != nil { + if exportDecl.ModuleSpecifier() != nil { topLevelExportGroups[groupIndex] = append(topLevelExportGroups[groupIndex], statements[i]) i++ } else { @@ -870,8 +870,8 @@ func coalesceExportsWorker( for _, exportDecl := range exportGroup { export := exportDecl.AsExportDeclaration() var moduleSpecifier string - if export.ModuleSpecifier != nil { - moduleSpecifier = export.ModuleSpecifier.Text() + if export.ModuleSpecifier() != nil { + moduleSpecifier = export.ModuleSpecifier().Text() } if _, exists := exportsByModuleSpecifier[moduleSpecifier]; !exists { moduleSpecifierOrder = append(moduleSpecifierOrder, moduleSpecifier) @@ -908,10 +908,10 @@ func coalesceExportsWorker( var newExportSpecifiers []*ast.Node for _, exportDecl := range subGroup { - exportClause := exportDecl.AsExportDeclaration().ExportClause + exportClause := exportDecl.AsExportDeclaration().ExportClause() if exportClause != nil && exportClause.Kind == ast.KindNamedExports { namedExports := exportClause.AsNamedExports() - newExportSpecifiers = append(newExportSpecifiers, namedExports.Elements.Nodes...) + newExportSpecifiers = append(newExportSpecifiers, namedExports.Elements().Nodes...) } } @@ -920,9 +920,9 @@ func coalesceExportsWorker( exportDecl := subGroup[0].AsExportDeclaration() var updatedExportClause *ast.NamedExportBindings - if exportDecl.ExportClause != nil { - if exportDecl.ExportClause.Kind == ast.KindNamedExports { - namedExports := exportDecl.ExportClause.AsNamedExports() + if exportDecl.ExportClause() != nil { + if exportDecl.ExportClause().Kind == ast.KindNamedExports { + namedExports := exportDecl.ExportClause().AsNamedExports() sortedList := factory.NewNodeList(newExportSpecifiers) updatedExportClause = factory.UpdateNamedExports(namedExports, sortedList) @@ -930,7 +930,7 @@ func coalesceExportsWorker( changeTracker.SetEmitFlags(updatedExportClause.AsNode(), printer.EFMultiLine) } } else { - updatedExportClause = exportDecl.ExportClause + updatedExportClause = exportDecl.ExportClause() } } @@ -939,8 +939,8 @@ func coalesceExportsWorker( exportDecl.Modifiers(), exportDecl.IsTypeOnly, updatedExportClause, - exportDecl.ModuleSpecifier, - exportDecl.Attributes, + exportDecl.ModuleSpecifier(), + exportDecl.Attributes(), ) coalescedExports = append(coalescedExports, newExportDecl) } @@ -961,7 +961,7 @@ func getCategorizedExports(exportGroup []*ast.Statement) categorizedExports { for _, exportDecl := range exportGroup { export := exportDecl.AsExportDeclaration() - if export.ExportClause == nil { + if export.ExportClause() == nil { if exportWithoutClause == nil { exportWithoutClause = exportDecl } diff --git a/tsc/internal/ls/rename.go b/tsc/internal/ls/rename.go index a41cea3ca0b8a..841e4ea8577a2 100644 --- a/tsc/internal/ls/rename.go +++ b/tsc/internal/ls/rename.go @@ -256,7 +256,7 @@ func wouldRenameInOtherNodeModules(originalFile *ast.SourceFile, symbol *ast.Sym sym := symbol if !preferences.ProvidePrefixAndSuffixTextForRename.IsTrueOrUnknown() && sym.Flags&ast.SymbolFlagsAlias != 0 { importSpecifier := core.Find(sym.Declarations, ast.IsImportSpecifier) - if importSpecifier != nil && importSpecifier.AsImportSpecifier().PropertyName == nil { + if importSpecifier != nil && importSpecifier.AsImportSpecifier().PropertyName() == nil { sym = ch.GetAliasedSymbol(sym) } } @@ -378,11 +378,11 @@ func (l *LanguageService) getTextForRename(originalNode *ast.Node, entry *Refere if useAliasesForRename && entry.kind != entryKindRange && (ast.IsIdentifier(originalNode) || ast.IsStringLiteralLike(originalNode)) { node := ast.GetReparsedNodeForNode(entry.node) kind := entry.kind - parent := node.Parent + parent := node.Parent() name := originalNode.Text() isShorthandAssignment := ast.IsShorthandPropertyAssignment(parent) switch { - case isShorthandAssignment || (isObjectBindingElementWithoutPropertyName(parent) && parent.Name() == node && parent.AsBindingElement().DotDotDotToken == nil): + case isShorthandAssignment || (isObjectBindingElementWithoutPropertyName(parent) && parent.Name() == node && parent.AsBindingElement().DotDotDotToken() == nil): if kind == entryKindSearchedLocalFoundProperty { return name + ": " + newText } @@ -392,8 +392,8 @@ func (l *LanguageService) getTextForRename(originalNode *ast.Node, entry *Refere // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. if isShorthandAssignment { - grandParent := parent.Parent - if ast.IsObjectLiteralExpression(grandParent) && ast.IsBinaryExpression(grandParent.Parent) && ast.IsModuleExportsAccessExpression(grandParent.Parent.AsBinaryExpression().Left) { + grandParent := parent.Parent() + if ast.IsObjectLiteralExpression(grandParent) && ast.IsBinaryExpression(grandParent.Parent()) && ast.IsModuleExportsAccessExpression(grandParent.Parent().AsBinaryExpression().Left()) { return name + ": " + newText } return newText + ": " + name @@ -402,8 +402,8 @@ func (l *LanguageService) getTextForRename(originalNode *ast.Node, entry *Refere case ast.IsImportSpecifier(parent) && parent.PropertyName() == nil: // If the original symbol was using this alias, just rename the alias. var originalSymbol *ast.Symbol - if ast.IsExportSpecifier(originalNode.Parent) { - originalSymbol = ch.GetExportSpecifierLocalTargetSymbol(originalNode.Parent) + if ast.IsExportSpecifier(originalNode.Parent()) { + originalSymbol = ch.GetExportSpecifierLocalTargetSymbol(originalNode.Parent()) } else { originalSymbol = ch.GetSymbolAtLocation(originalNode) } @@ -421,7 +421,7 @@ func (l *LanguageService) getTextForRename(originalNode *ast.Node, entry *Refere } // If the node is a numerical indexing literal, then add quotes around the property access. - if entry.kind != entryKindRange && ast.IsNumericLiteral(entry.node) && ast.IsAccessExpression(entry.node.Parent) { + if entry.kind != entryKindRange && ast.IsNumericLiteral(entry.node) && ast.IsAccessExpression(entry.node.Parent()) { quote := getQuoteFromPreference(quotePreference) return quote + newText + quote } diff --git a/tsc/internal/ls/selectionranges.go b/tsc/internal/ls/selectionranges.go index a8468baa9221b..a19bf56306d84 100644 --- a/tsc/internal/ls/selectionranges.go +++ b/tsc/internal/ls/selectionranges.go @@ -87,9 +87,9 @@ func getSelectionChildren(factory *ast.NodeFactory, node *ast.Node, sourceFile * // Group `-/+readonly` and `-/+?`. groupedWithPlusMinusTokens := groupChildren(factory, children, func(child *ast.Node) bool { - return child == mappedType.ReadonlyToken || + return child == mappedType.ReadonlyToken() || child.Kind == ast.KindReadonlyKeyword || - child == mappedType.QuestionToken || + child == mappedType.QuestionToken() || child.Kind == ast.KindQuestionToken }) @@ -271,7 +271,7 @@ func getSmartSelectionRange(l *LanguageService, sourceFile *ast.SourceFile, pos // Skip lone variable declarations if parent != nil && ast.IsVariableDeclaration(node) && ast.IsVariableDeclarationList(parent) { decl := parent.AsVariableDeclarationList() - if decl != nil && len(decl.Declarations.Nodes) == 1 { + if decl != nil && len(decl.Declarations().Nodes) == 1 { return true } } @@ -312,12 +312,12 @@ func getSmartSelectionRange(l *LanguageService, sourceFile *ast.SourceFile, pos // Synthesize a stop for '${ ... }' since '${' and '}' actually belong to siblings. if ast.IsTemplateSpan(parent) { templateSpan := parent.AsTemplateSpan() - if templateSpan.Literal != nil { + if templateSpan.Literal() != nil { // Start from just before the '${' and end after the '}' // The '${' is 2 characters before the expression start spanStart := node.Pos() - 2 // The '}' is the first character of the template literal (middle or tail) - spanEnd := astnav.GetStartOfNode(templateSpan.Literal, sourceFile, false) + 1 + spanEnd := astnav.GetStartOfNode(templateSpan.Literal(), sourceFile, false) + 1 // Validate the positions are reasonable text := sourceFile.Text() if spanStart >= 0 && spanEnd <= len(text) && spanStart < spanEnd { diff --git a/tsc/internal/ls/semantictokens.go b/tsc/internal/ls/semantictokens.go index 24d4ca9c89f59..54b8312962601 100644 --- a/tsc/internal/ls/semantictokens.go +++ b/tsc/internal/ls/semantictokens.go @@ -266,7 +266,7 @@ func (l *LanguageService) collectSemanticTokensInRange(ctx context.Context, c *c tokenModifier := tokenModifier(0) // Check if this is a declaration - parent := node.Parent + parent := node.Parent() if parent != nil { parentIsDeclaration := ast.IsBindingElement(parent) || tokenFromDeclarationMapping(parent.Kind) == tokenType if parentIsDeclaration && parent.Name() == node { @@ -466,21 +466,21 @@ func isLocalDeclaration(decl *ast.Node, sourceFile *ast.SourceFile) bool { decl = getDeclarationForBindingElement(decl) } if ast.IsVariableDeclaration(decl) { - parent := decl.Parent + parent := decl.Parent() // Check if this is a catch clause parameter if parent != nil && ast.IsCatchClause(parent) { return ast.GetSourceFileOfNode(decl) == sourceFile } if parent != nil && ast.IsVariableDeclarationList(parent) { - grandparent := parent.Parent + grandparent := parent.Parent() if grandparent != nil { - greatGrandparent := grandparent.Parent + greatGrandparent := grandparent.Parent() return (!ast.IsSourceFile(greatGrandparent) || ast.IsCatchClause(grandparent)) && ast.GetSourceFileOfNode(decl) == sourceFile } } } else if ast.IsFunctionDeclaration(decl) { - parent := decl.Parent + parent := decl.Parent() return parent != nil && !ast.IsSourceFile(parent) && ast.GetSourceFileOfNode(decl) == sourceFile } return false @@ -488,29 +488,29 @@ func isLocalDeclaration(decl *ast.Node, sourceFile *ast.SourceFile) bool { func getDeclarationForBindingElement(element *ast.Node) *ast.Node { for { - parent := element.Parent + parent := element.Parent() if parent != nil && ast.IsBindingPattern(parent) { - grandparent := parent.Parent + grandparent := parent.Parent() if grandparent != nil && ast.IsBindingElement(grandparent) { element = grandparent continue } - return parent.Parent + return parent.Parent() } return element } } func isInImportClause(node *ast.Node) bool { - parent := node.Parent + parent := node.Parent() return parent != nil && (ast.IsImportClause(parent) || ast.IsImportSpecifier(parent) || ast.IsNamespaceImport(parent)) } func isExpressionInCallExpression(node *ast.Node) bool { for ast.IsRightSideOfQualifiedNameOrPropertyAccess(node) { - node = node.Parent + node = node.Parent() } - parent := node.Parent + parent := node.Parent() return parent != nil && ast.IsCallExpression(parent) && parent.Expression() == node } diff --git a/tsc/internal/ls/signaturehelp.go b/tsc/internal/ls/signaturehelp.go index 6e1fce510d96c..7cf644f88df03 100644 --- a/tsc/internal/ls/signaturehelp.go +++ b/tsc/internal/ls/signaturehelp.go @@ -793,7 +793,7 @@ func getCandidateOrTypeInfo(info *argumentListInfo, c *checker.Checker, sourceFi called := info.invocation.typeArgsInvocation.called.AsNode() container := called if ast.IsIdentifier(called) { - container = called.Parent + container = called.Parent() } if onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, container) { @@ -854,23 +854,23 @@ func containsPrecedingToken(startingToken *ast.Node, sourceFile *ast.SourceFile, // case, the preceding token we want is actually higher up the tree—almost definitely the // next parent, but theoretically the situation with missing nodes might be happening on // multiple nested levels. - currentParent := startingToken.Parent + currentParent := startingToken.Parent() for currentParent != nil { precedingToken := astnav.FindPrecedingTokenEx(sourceFile, pos, currentParent, true /*excludeJSDoc*/) if precedingToken != nil { return RangeContainsRange(container.Loc, precedingToken.Loc) } - currentParent = currentParent.Parent + currentParent = currentParent.Parent() } return false } func getContainingArgumentInfo(node *ast.Node, sourceFile *ast.SourceFile, checker *checker.Checker, isManuallyInvoked bool, position int) *argumentListInfo { var firstArgumentInfo *argumentListInfo - for n := node; !ast.IsSourceFile(n) && (isManuallyInvoked || !ast.IsBlock(n)); n = n.Parent { + for n := node; !ast.IsSourceFile(n) && (isManuallyInvoked || !ast.IsBlock(n)); n = n.Parent() { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. - debug.Assert(RangeContainsRange(n.Parent.Loc, n.Loc), "Not a subspan. Child: ", n.KindString(), ", parent: ", n.Parent.KindString()) + debug.Assert(RangeContainsRange(n.Parent().Loc, n.Loc), "Not a subspan. Child: ", n.KindString(), ", parent: ", n.Parent().KindString()) argumentInfo := getImmediatelyContainingArgumentOrContextualParameterInfo(n, position, sourceFile, checker) if argumentInfo != nil { // For contextual invocations (e.g., arrow functions with contextual types), @@ -928,7 +928,7 @@ type argumentListInfo struct { // Returns relevant information for the argument list and the current argument if we are // in the argument of an invocation; returns undefined otherwise. func getImmediatelyContainingArgumentInfo(node *ast.Node, position int, sourceFile *ast.SourceFile, c *checker.Checker) *argumentListInfo { - parent := node.Parent + parent := node.Parent() if ast.IsCallOrNewExpression(parent) { // There are 3 cases to handle: // 1. The token introduces a list, and should begin a signature help session @@ -973,25 +973,25 @@ func getImmediatelyContainingArgumentInfo(node *ast.Node, position int, sourceFi return getArgumentListInfoForTemplate(parent.AsTaggedTemplateExpression(), 0, sourceFile) } return nil - } else if isTemplateHead(node) && parent.Parent.Kind == ast.KindTaggedTemplateExpression { + } else if isTemplateHead(node) && parent.Parent().Kind == ast.KindTaggedTemplateExpression { templateExpression := parent.AsTemplateExpression() - tagExpression := templateExpression.Parent.AsTaggedTemplateExpression() + tagExpression := templateExpression.Parent().AsTaggedTemplateExpression() argumentIndex := 1 if isInsideTemplateLiteral(node, position, sourceFile) { argumentIndex = 0 } return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile) - } else if ast.IsTemplateSpan(parent) && isTaggedTemplateExpression(parent.Parent.Parent) { + } else if ast.IsTemplateSpan(parent) && isTaggedTemplateExpression(parent.Parent().Parent()) { templateSpan := parent - tagExpression := parent.Parent.Parent + tagExpression := parent.Parent().Parent() // If we're just after a template tail, don't show signature help. if isTemplateTail(node) && !isInsideTemplateLiteral(node, position, sourceFile) { return nil } - spanIndex := ast.IndexOfNode(templateSpan.Parent.AsTemplateExpression().TemplateSpans.Nodes, templateSpan) + spanIndex := ast.IndexOfNode(templateSpan.Parent().AsTemplateExpression().TemplateSpans().Nodes, templateSpan) argumentIndex := getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile) return getArgumentListInfoForTemplate(tagExpression.AsTaggedTemplateExpression(), argumentIndex, sourceFile) @@ -1060,7 +1060,7 @@ func getAdjustedNode(node *ast.Node) *ast.Node { case ast.KindOpenParenToken, ast.KindCommaToken: return node default: - return ast.FindAncestor(node.Parent, func(n *ast.Node) bool { + return ast.FindAncestor(node.Parent(), func(n *ast.Node) bool { if ast.IsParameterDeclaration(n) { return true } else if ast.IsBindingElement(n) || ast.IsObjectBindingPattern(n) || ast.IsArrayBindingPattern(n) { @@ -1079,7 +1079,7 @@ type contextualSignatureLocationInfo struct { } func getSpreadElementCount(node *ast.SpreadElement, c *checker.Checker) int { - spreadType := c.GetTypeAtLocation(node.Expression) + spreadType := c.GetTypeAtLocation(node.Expression()) if checker.IsTupleType(spreadType) { tupleType := spreadType.Target().AsTupleType() if tupleType == nil { @@ -1103,11 +1103,11 @@ func getSpreadElementCount(node *ast.SpreadElement, c *checker.Checker) int { } func getArgumentIndex(node *ast.Node, arguments *ast.NodeList, sourceFile *ast.SourceFile, c *checker.Checker) int { - return getArgumentIndexOrCount(getTokenFromNodeList(arguments, node.Parent, sourceFile), node, c) + return getArgumentIndexOrCount(getTokenFromNodeList(arguments, node.Parent(), sourceFile), node, c) } func getArgumentCount(node *ast.Node, arguments *ast.NodeList, sourceFile *ast.SourceFile, c *checker.Checker) int { - return getArgumentIndexOrCount(getTokenFromNodeList(arguments, node.Parent, sourceFile), nil, c) + return getArgumentIndexOrCount(getTokenFromNodeList(arguments, node.Parent(), sourceFile), nil, c) } func getArgumentIndexOrCount(arguments []*ast.Node, node *ast.Node, c *checker.Checker) int { @@ -1224,7 +1224,7 @@ func getArgumentOrParameterListAndIndex(node *ast.Node, sourceFile *ast.SourceFi if node.Kind == ast.KindLessThanToken || node.Kind == ast.KindOpenParenToken { // Find the list that starts right *after* the < or ( token. // If the user has just opened a list, consider this item 0. - list := getChildListThatStartsWithOpenerToken(node.Parent, node) + list := getChildListThatStartsWithOpenerToken(node.Parent(), node) return &argumentOrParameterListAndIndex{ list: list, argumentIndex: 0, @@ -1254,13 +1254,13 @@ func getChildListThatStartsWithOpenerToken(parent *ast.Node, openerToken *ast.No if openerToken.Kind == ast.KindLessThanToken { return parentCallExpression.TypeArgumentList() } - return parentCallExpression.Arguments + return parentCallExpression.Arguments() } else if ast.IsNewExpression(parent) { parentNewExpression := parent.AsNewExpression() if openerToken.Kind == ast.KindLessThanToken { return parentNewExpression.TypeArgumentList() } - return parentNewExpression.Arguments + return parentNewExpression.Arguments() } return nil } @@ -1309,8 +1309,8 @@ func tryGetParameterInfo(startingToken *ast.Node, sourceFile *ast.SourceFile, c func chooseBetterSymbol(s *ast.Symbol) *ast.Symbol { if s.Name == ast.InternalSymbolNameType { for _, d := range s.Declarations { - if ast.IsFunctionTypeNode(d) && ast.CanHaveSymbol(d.Parent) { - return d.Parent.Symbol() + if ast.IsFunctionTypeNode(d) && ast.CanHaveSymbol(d.Parent()) { + return d.Parent().Symbol() } } } @@ -1318,7 +1318,7 @@ func chooseBetterSymbol(s *ast.Symbol) *ast.Symbol { } func getContextualSignatureLocationInfo(node *ast.Node, sourceFile *ast.SourceFile, c *checker.Checker) *contextualSignatureLocationInfo { - parent := node.Parent + parent := node.Parent() switch parent.Kind { case ast.KindParenthesizedExpression, ast.KindMethodDeclaration, ast.KindFunctionExpression, ast.KindArrowFunction: info := getArgumentOrParameterListInfo(node, sourceFile, c) @@ -1366,15 +1366,15 @@ func getContextualSignatureLocationInfo(node *ast.Node, sourceFile *ast.SourceFi } func getHighestBinary(b *ast.BinaryExpression) *ast.BinaryExpression { - if ast.IsBinaryExpression(b.Parent) { - return getHighestBinary(b.Parent.AsBinaryExpression()) + if ast.IsBinaryExpression(b.Parent()) { + return getHighestBinary(b.Parent().AsBinaryExpression()) } return b } func countBinaryExpressionParameters(b *ast.BinaryExpression) int { - if ast.IsBinaryExpression(b.Left) { - return countBinaryExpressionParameters(b.Left.AsBinaryExpression()) + 1 + if ast.IsBinaryExpression(b.Left()) { + return countBinaryExpressionParameters(b.Left().AsBinaryExpression()) + 1 } return 2 } @@ -1406,8 +1406,8 @@ func getTokenFromNodeList(nodeList *ast.NodeList, nodeListParent *ast.Node, sour func getArgumentListInfoForTemplate(tagExpression *ast.TaggedTemplateExpression, argumentIndex int, sourceFile *ast.SourceFile) *argumentListInfo { // argumentCount is either 1 or (numSpans + 1) to account for the template strings array argument. argumentCount := 1 - if !isNoSubstitutionTemplateLiteral(tagExpression.Template) { - argumentCount = len(tagExpression.Template.AsTemplateExpression().TemplateSpans.Nodes) + 1 + if !isNoSubstitutionTemplateLiteral(tagExpression.Template()) { + argumentCount = len(tagExpression.Template().AsTemplateExpression().TemplateSpans().Nodes) + 1 } if argumentIndex != 0 { debug.Assert(argumentIndex < argumentCount) @@ -1422,7 +1422,7 @@ func getArgumentListInfoForTemplate(tagExpression *ast.TaggedTemplateExpression, } func getApplicableRangeForTaggedTemplate(taggedTemplate *ast.TaggedTemplateExpression, sourceFile *ast.SourceFile) core.TextRange { - template := taggedTemplate.Template + template := taggedTemplate.Template() applicableSpanStart := scanner.GetTokenPosOfNode(template, sourceFile, false) applicableSpanEnd := template.End() @@ -1435,9 +1435,9 @@ func getApplicableRangeForTaggedTemplate(taggedTemplate *ast.TaggedTemplateExpre // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. if template.Kind == ast.KindTemplateExpression { - templateSpans := template.AsTemplateExpression().TemplateSpans + templateSpans := template.AsTemplateExpression().TemplateSpans() lastSpan := templateSpans.Nodes[len(templateSpans.Nodes)-1] - if lastSpan.AsTemplateSpan().Literal.End()-lastSpan.AsTemplateSpan().Literal.Pos() == 0 { + if lastSpan.AsTemplateSpan().Literal().End()-lastSpan.AsTemplateSpan().Literal().Pos() == 0 { applicableSpanEnd = scanner.SkipTrivia(sourceFile.Text(), applicableSpanEnd) } } diff --git a/tsc/internal/ls/sourcedefinition.go b/tsc/internal/ls/sourcedefinition.go index 2ad3e3808b9b7..fa7d95e230fed 100644 --- a/tsc/internal/ls/sourcedefinition.go +++ b/tsc/internal/ls/sourcedefinition.go @@ -67,7 +67,7 @@ func (l *LanguageService) provideSourceDefinitionAtPosition( originSelectionRange, _ := l.createLspRangeFromNode(node, file) containingModuleSpecifier := findContainingModuleSpecifier(node) - if containingModuleSpecifier != nil && ast.IsSourcePhaseImport(containingModuleSpecifier.Parent) { + if containingModuleSpecifier != nil && ast.IsSourcePhaseImport(containingModuleSpecifier.Parent()) { return l.provideDefinitionAtPosition(ctx, program, file, textPos, clientSupportsLink), nil } @@ -226,9 +226,9 @@ func getSourceDefCheckerInfo( defer done() declarations := getDeclarationsFromLocation(c, node) - isPropertyName := node.Parent != nil && ast.IsAccessExpression(node.Parent) && node.Parent.Name() == node + isPropertyName := node.Parent() != nil && ast.IsAccessExpression(node.Parent()) && node.Parent().Name() == node if len(declarations) == 0 && isPropertyName { - if left := node.Parent.Expression(); left != nil { + if left := node.Parent().Expression(); left != nil { if prop := c.GetPropertyOfType(c.GetTypeAtLocation(left), node.Text()); prop != nil { declarations = prop.Declarations } @@ -245,7 +245,7 @@ func getSourceDefCheckerInfo( var moduleSpecifier string resolveNode := node if isPropertyName { - expr := node.Parent.Expression() + expr := node.Parent().Expression() for expr != nil && ast.IsAccessExpression(expr) { expr = expr.Expression() } @@ -331,10 +331,10 @@ func (r *sourceDefResolver) searchImplementationFile( } func isDefaultImportName(node *ast.Node) bool { - if node == nil || node.Parent == nil || !ast.IsImportClause(node.Parent) || node.Parent.Name() != node || node.Parent.Parent == nil { + if node == nil || node.Parent() == nil || !ast.IsImportClause(node.Parent()) || node.Parent().Name() != node || node.Parent().Parent() == nil { return false } - return ast.IsDefaultImport(node.Parent.Parent) + return ast.IsDefaultImport(node.Parent().Parent()) } func getSourceDefinitionEntryNode(sourceFile *ast.SourceFile) *ast.Node { @@ -487,7 +487,7 @@ func (r *sourceDefResolver) inferImpliedNodeFormat(fileName tspath.RootedFilePat } func findContainingModuleSpecifier(node *ast.Node) *ast.Node { - for current := node; current != nil; current = current.Parent { + for current := node; current != nil; current = current.Parent() { if ast.IsAnyImportOrReExport(current) || ast.IsRequireCall(current, true /*requireStringLiteralLikeArgument*/) || ast.IsImportCall(current) { if moduleSpecifier := ast.GetExternalModuleName(current); moduleSpecifier != nil && ast.IsStringLiteralLike(moduleSpecifier) { return moduleSpecifier @@ -572,9 +572,9 @@ func getCandidateSourceDeclarationNames(originalNode *ast.Node, declaration *ast if isDefaultImportName(originalNode) { names = append(names, "default") } - if originalNode.Parent != nil { - if ast.IsImportSpecifier(originalNode.Parent) || ast.IsExportSpecifier(originalNode.Parent) { - if propName := originalNode.Parent.PropertyName(); propName != nil { + if originalNode.Parent() != nil { + if ast.IsImportSpecifier(originalNode.Parent()) || ast.IsExportSpecifier(originalNode.Parent()) { + if propName := originalNode.Parent().PropertyName(); propName != nil { names = append(names, propName.Text()) } } @@ -669,7 +669,7 @@ func filterPreferredSourceDeclarations(originalNode *ast.Node, declarations []*a } func getPropertyLikeSourceDeclarations(originalNode *ast.Node, declarations []*ast.Node) []*ast.Node { - if originalNode.Parent == nil || !ast.IsAccessExpression(originalNode.Parent) || originalNode.Parent.Name() != originalNode { + if originalNode.Parent() == nil || !ast.IsAccessExpression(originalNode.Parent()) || originalNode.Parent().Name() != originalNode { return nil } return core.Filter(declarations, func(node *ast.Node) bool { @@ -740,7 +740,7 @@ func uniqueDeclarationNodes(nodes []*ast.Node) []*ast.Node { func findClosestDeclarationNode(sourceFile *ast.SourceFile, pos int) *ast.Node { node := astnav.GetTouchingPropertyName(sourceFile, pos) - for current := node; current != nil; current = current.Parent { + for current := node; current != nil; current = current.Parent() { if ast.IsDeclaration(current) || current.Kind == ast.KindExportAssignment { return current } diff --git a/tsc/internal/ls/string_completions.go b/tsc/internal/ls/string_completions.go index dafb552280c38..78686e4ad5961 100644 --- a/tsc/internal/ls/string_completions.go +++ b/tsc/internal/ls/string_completions.go @@ -267,10 +267,10 @@ func (l *LanguageService) getStringLiteralCompletionEntries( position int, typeChecker *checker.Checker, ) *stringLiteralCompletions { - parent := walkUpParentheses(node.Parent) + parent := walkUpParentheses(node.Parent()) switch parent.Kind { case ast.KindLiteralType: - grandparent := walkUpParentheses(parent.Parent) + grandparent := walkUpParentheses(parent.Parent()) if grandparent.Kind == ast.KindImportType { return l.getStringLiteralCompletionsFromModuleNames( file, @@ -281,7 +281,7 @@ func (l *LanguageService) getStringLiteralCompletionEntries( } return fromUnionableLiteralType(grandparent, parent, position, typeChecker) case ast.KindPropertyAssignment: - if ast.IsObjectLiteralExpression(parent.Parent) && parent.Name() == node { + if ast.IsObjectLiteralExpression(parent.Parent()) && parent.Name() == node { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -295,10 +295,10 @@ func (l *LanguageService) getStringLiteralCompletionEntries( // '/*completion position*/' // }); return &stringLiteralCompletions{ - fromProperties: stringLiteralCompletionsForObjectLiteral(typeChecker, parent.Parent), + fromProperties: stringLiteralCompletionsForObjectLiteral(typeChecker, parent.Parent()), } } - if ast.FindAncestor(parent.Parent, ast.IsCallLikeExpression) != nil { + if ast.FindAncestor(parent.Parent(), ast.IsCallLikeExpression) != nil { uniques := &collections.Set[string]{} stringLiteralTypes := append( getStringLiteralTypes(typeChecker.GetContextualType(node, checker.ContextFlagsNone), uniques, typeChecker), @@ -311,7 +311,7 @@ func (l *LanguageService) getStringLiteralCompletionEntries( } case ast.KindElementAccessExpression: expression := parent.Expression() - argumentExpression := parent.AsElementAccessExpression().ArgumentExpression + argumentExpression := parent.AsElementAccessExpression().ArgumentExpression() if node == ast.SkipParentheses(argumentExpression) { // Get all names of properties on the expression // i.e. interface A { @@ -329,7 +329,7 @@ func (l *LanguageService) getStringLiteralCompletionEntries( if !isRequireCallArgument(node) && !ast.IsImportCall(parent) { var argumentNode *ast.Node if parent.Kind == ast.KindJsxAttribute { - argumentNode = parent.Parent + argumentNode = parent.Parent() } else { argumentNode = node } @@ -361,7 +361,7 @@ func (l *LanguageService) getStringLiteralCompletionEntries( // export * from "/*completion position*/"; return l.getStringLiteralCompletionsFromModuleNames(file, node, l.GetProgram(), typeChecker) case ast.KindCaseClause: - tracker := newCaseClauseTracker(typeChecker, parent.Parent.AsCaseBlock().Clauses.Nodes) + tracker := newCaseClauseTracker(typeChecker, parent.Parent().AsCaseBlock().Clauses().Nodes) contextualTypes := fromContextualType(checker.ContextFlagsIgnoreNodeInferences, node, typeChecker) if contextualTypes == nil { return nil @@ -381,12 +381,12 @@ func (l *LanguageService) getStringLiteralCompletionEntries( if propertyName := specifier.PropertyName(); propertyName != nil && node != propertyName { return nil // Don't complete in `export { "..." as "|" } from` } - namedImportsOrExports := specifier.Parent + namedImportsOrExports := specifier.Parent() var moduleSpecifier *ast.Node if namedImportsOrExports.Kind == ast.KindNamedImports { - moduleSpecifier = namedImportsOrExports.Parent.Parent + moduleSpecifier = namedImportsOrExports.Parent().Parent() } else { - moduleSpecifier = namedImportsOrExports.Parent + moduleSpecifier = namedImportsOrExports.Parent() } if moduleSpecifier == nil { return nil @@ -409,8 +409,8 @@ func (l *LanguageService) getStringLiteralCompletionEntries( }, } case ast.KindBinaryExpression: - if parent.AsBinaryExpression().OperatorToken.Kind == ast.KindInKeyword { - t := typeChecker.GetTypeAtLocation(parent.AsBinaryExpression().Right) + if parent.AsBinaryExpression().OperatorToken().Kind == ast.KindInKeyword { + t := typeChecker.GetTypeAtLocation(parent.AsBinaryExpression().Right()) properties := getPropertiesForCompletion(t, typeChecker) return &stringLiteralCompletions{ fromProperties: &completionsFromProperties{ @@ -477,7 +477,7 @@ func fromUnionableLiteralType( ast.KindNewExpression, ast.KindTaggedTemplateExpression, ast.KindTypeReference: - typeArgument := ast.FindAncestor(parent, func(n *ast.Node) bool { return n.Parent == grandparent }) + typeArgument := ast.FindAncestor(parent, func(n *ast.Node) bool { return n.Parent() == grandparent }) if typeArgument != nil { t := typeChecker.GetTypeArgumentConstraint(typeArgument) return &stringLiteralCompletions{ @@ -495,8 +495,8 @@ func fromUnionableLiteralType( // bar: string; // } // let x: Foo["/*completion position*/"] - indexType := grandparent.AsIndexedAccessTypeNode().IndexType - objectType := grandparent.AsIndexedAccessTypeNode().ObjectType + indexType := grandparent.AsIndexedAccessTypeNode().IndexType() + objectType := grandparent.AsIndexedAccessTypeNode().ObjectType() if !indexType.Loc.ContainsInclusive(position) { return nil } @@ -506,7 +506,7 @@ func fromUnionableLiteralType( } case ast.KindUnionType: result := fromUnionableLiteralType( - walkUpParentheses(grandparent.Parent), + walkUpParentheses(grandparent.Parent()), parent, position, typeChecker, @@ -1943,15 +1943,15 @@ func getStringLiteralTypes(t *checker.Type, uniques *collections.Set[string], ty } func getAlreadyUsedTypesInStringLiteralUnion(union *ast.UnionTypeNodeNode, current *ast.LiteralTypeNodeNode) []string { - typesList := union.AsUnionTypeNode().Types + typesList := union.AsUnionTypeNode().Types() if typesList == nil { return nil } var values []string for _, typeNode := range typesList.Nodes { if typeNode != current && ast.IsLiteralTypeNode(typeNode) && - ast.IsStringLiteral(typeNode.AsLiteralTypeNode().Literal) { - values = append(values, typeNode.AsLiteralTypeNode().Literal.Text()) + ast.IsStringLiteral(typeNode.AsLiteralTypeNode().Literal()) { + values = append(values, typeNode.AsLiteralTypeNode().Literal().Text()) } } return values @@ -1966,8 +1966,8 @@ func hasIndexSignature(t *checker.Type, typeChecker *checker.Checker) bool { // require("" // require("") func isRequireCallArgument(node *ast.Node) bool { - return ast.IsCallExpression(node.Parent) && len(node.Parent.Arguments()) > 0 && node.Parent.Arguments()[0] == node && - ast.IsIdentifier(node.Parent.Expression()) && node.Parent.Expression().Text() == "require" + return ast.IsCallExpression(node.Parent()) && len(node.Parent().Arguments()) > 0 && node.Parent().Arguments()[0] == node && + ast.IsIdentifier(node.Parent().Expression()) && node.Parent().Expression().Text() == "require" } func kindModifiersFromExtension(extension string) lsutil.ScriptElementKindModifier { @@ -2013,7 +2013,7 @@ func getStringLiteralCompletionsFromSignature( uniques := collections.Set[string]{} var editingArgument *ast.Node if ast.IsJsxOpeningLikeElement(call) { - editingArgument = ast.FindAncestor(arg.Parent, ast.IsJsxAttribute) + editingArgument = ast.FindAncestor(arg.Parent(), ast.IsJsxAttribute) if editingArgument == nil { panic("Expected jsx opening-like element to have a jsx attribute as ancestor.") } diff --git a/tsc/internal/ls/symbols.go b/tsc/internal/ls/symbols.go index 041dc9ab21cc6..2009c5ed5b6d7 100644 --- a/tsc/internal/ls/symbols.go +++ b/tsc/internal/ls/symbols.go @@ -151,7 +151,7 @@ func (l *LanguageService) getDocumentSymbolsForChildren(ctx context.Context, nod if node.Flags&ast.NodeFlagsReparsed == 0 { if jsdocs := node.JSDoc(file); len(jsdocs) > 0 { for _, jsdoc := range jsdocs { - if tagList := jsdoc.AsJSDoc().Tags; tagList != nil { + if tagList := jsdoc.AsJSDoc().Tags(); tagList != nil { for _, tag := range tagList.Nodes { if ast.IsJSDocTypedefTag(tag) || ast.IsJSDocCallbackTag(tag) { addSymbolForNode(tag, nil /*name*/, nil /*children*/) @@ -161,7 +161,7 @@ func (l *LanguageService) getDocumentSymbolsForChildren(ctx context.Context, nod } } } - if node.Parent.Kind == ast.KindSourceFile && ast.IsImportOrImportEqualsDeclaration(node) { + if node.Parent().Kind == ast.KindSourceFile && ast.IsImportOrImportEqualsDeclaration(node) { return false } switch node.Kind { @@ -209,7 +209,7 @@ func (l *LanguageService) getDocumentSymbolsForChildren(ctx context.Context, nod // Handle named bindings in imports e.g.: // import * as NS from "mod"; // import {a, b as B} from "mod"; - if namedBindings := node.AsImportClause().NamedBindings; namedBindings != nil { + if namedBindings := node.AsImportClause().NamedBindings(); namedBindings != nil { if namedBindings.Kind == ast.KindNamespaceImport { addSymbolForNode(namedBindings, nil /*name*/, nil /*children*/) } else { @@ -235,14 +235,14 @@ func (l *LanguageService) getDocumentSymbolsForChildren(ctx context.Context, nod // `A.b = ... ` or `A.prototype.b = ...` if ast.IsBinaryExpression(node) { binaryExpr := node.AsBinaryExpression() - target = binaryExpr.Left + target = binaryExpr.Left() targetFunction = target.Expression() - definition = binaryExpr.Right + definition = binaryExpr.Right() // `A.b` or `A.prototype.b` if ast.IsPropertyAccessExpression(target) { propertyName = target.AsPropertyAccessExpression().Name() } else { // `A["b"]` or `A.prototype["b"]` - propertyName = target.AsElementAccessExpression().ArgumentExpression + propertyName = target.AsElementAccessExpression().ArgumentExpression() } } else { // `Object.defineProperty(A, "b", {...})` args := node.Arguments() @@ -447,7 +447,7 @@ func getTextOfName(node *ast.Node) string { } func getUnnamedNodeLabel(node *ast.Node) string { - if parent := ast.WalkUpParenthesizedExpressions(node.Parent); parent != nil && ast.IsExportAssignment(parent) { + if parent := ast.WalkUpParenthesizedExpressions(node.Parent()); parent != nil && ast.IsExportAssignment(parent) { if parent.AsExportAssignment().IsExportEquals { return "export=" } @@ -458,14 +458,14 @@ func getUnnamedNodeLabel(node *ast.Node) string { if node.ModifierFlags()&ast.ModifierFlagsDefault != 0 { return "default" } - if ast.IsCallExpression(node.Parent) { - name := getCallExpressionName(node.Parent.Expression()) + if ast.IsCallExpression(node.Parent()) { + name := getCallExpressionName(node.Parent().Expression()) if name != "" { name = cleanCallbackText(name) if len(name) > maxLength { return name + " callback" } - args := cleanCallbackText(getCallExpressionLiteralArgs(node.Parent)) + args := cleanCallbackText(getCallExpressionLiteralArgs(node.Parent())) return name + "(" + args + ") callback" } } diff --git a/tsc/internal/ls/utilities.go b/tsc/internal/ls/utilities.go index 1ba73cc62d9fd..02aba2781d50a 100644 --- a/tsc/internal/ls/utilities.go +++ b/tsc/internal/ls/utilities.go @@ -50,13 +50,13 @@ func isModuleSpecifierLike(node *ast.Node) bool { return false } - if ast.IsRequireCall(node.Parent, false /*requireStringLiteralLikeArgument*/) || ast.IsImportCall(node.Parent) { - return node.Parent.Arguments()[0] == node + if ast.IsRequireCall(node.Parent(), false /*requireStringLiteralLikeArgument*/) || ast.IsImportCall(node.Parent()) { + return node.Parent().Arguments()[0] == node } - return node.Parent.Kind == ast.KindExternalModuleReference || - node.Parent.Kind == ast.KindImportDeclaration || - node.Parent.Kind == ast.KindJSImportDeclaration + return node.Parent().Kind == ast.KindExternalModuleReference || + node.Parent().Kind == ast.KindImportDeclaration || + node.Parent().Kind == ast.KindJSImportDeclaration } func getNonModuleSymbolOfMergedModuleSymbol(symbol *ast.Symbol) *ast.Symbol { @@ -80,15 +80,15 @@ func getLocalSymbolForExportSpecifier(referenceLocation *ast.Node, referenceSymb } func isExportSpecifierAlias(referenceLocation *ast.Node, exportSpecifier *ast.ExportSpecifier) bool { - debug.Assert(exportSpecifier.PropertyName == referenceLocation || exportSpecifier.Name() == referenceLocation, "referenceLocation is not export specifier name or property name") - propertyName := exportSpecifier.PropertyName + debug.Assert(exportSpecifier.PropertyName() == referenceLocation || exportSpecifier.Name() == referenceLocation, "referenceLocation is not export specifier name or property name") + propertyName := exportSpecifier.PropertyName() if propertyName != nil { // Given `export { foo as bar } [from "someModule"]`: It's an alias at `foo`, but at `bar` it's a new symbol. return propertyName == referenceLocation } else { // `export { foo } from "foo"` is a re-export. // `export { foo };` is not a re-export, it creates an alias for the local variable `foo`. - return exportSpecifier.Parent.Parent.ModuleSpecifier() == nil + return exportSpecifier.Parent().Parent().ModuleSpecifier() == nil } } @@ -189,14 +189,14 @@ func getPossibleTypeArgumentsInfo(tokenIn *ast.Node, sourceFile *ast.SourceFile) } func isNameOfModuleDeclaration(node *ast.Node) bool { - if node.Parent.Kind != ast.KindModuleDeclaration { + if node.Parent().Kind != ast.KindModuleDeclaration { return false } - return node.Parent.Name() == node + return node.Parent().Name() == node } func isExpressionOfExternalModuleImportEqualsDeclaration(node *ast.Node) bool { - return ast.IsExternalModuleImportEqualsDeclaration(node.Parent.Parent) && ast.GetExternalModuleImportEqualsDeclarationExpression(node.Parent.Parent) == node + return ast.IsExternalModuleImportEqualsDeclaration(node.Parent().Parent()) && ast.GetExternalModuleImportEqualsDeclarationExpression(node.Parent().Parent()) == node } func isNamespaceReference(node *ast.Node) bool { @@ -206,32 +206,32 @@ func isNamespaceReference(node *ast.Node) bool { func isQualifiedNameNamespaceReference(node *ast.Node) bool { root := node isLastClause := true - if root.Parent.Kind == ast.KindQualifiedName { - for root.Parent != nil && root.Parent.Kind == ast.KindQualifiedName { - root = root.Parent + if root.Parent().Kind == ast.KindQualifiedName { + for root.Parent() != nil && root.Parent().Kind == ast.KindQualifiedName { + root = root.Parent() } - isLastClause = root.AsQualifiedName().Right == node + isLastClause = root.AsQualifiedName().Right() == node } - return root.Parent.Kind == ast.KindTypeReference && !isLastClause + return root.Parent().Kind == ast.KindTypeReference && !isLastClause } func isPropertyAccessNamespaceReference(node *ast.Node) bool { root := node isLastClause := true - if root.Parent.Kind == ast.KindPropertyAccessExpression { - for root.Parent != nil && root.Parent.Kind == ast.KindPropertyAccessExpression { - root = root.Parent + if root.Parent().Kind == ast.KindPropertyAccessExpression { + for root.Parent() != nil && root.Parent().Kind == ast.KindPropertyAccessExpression { + root = root.Parent() } isLastClause = root.Name() == node } - if !isLastClause && root.Parent.Kind == ast.KindExpressionWithTypeArguments && root.Parent.Parent.Kind == ast.KindHeritageClause { - decl := root.Parent.Parent.Parent - return (decl.Kind == ast.KindClassDeclaration && root.Parent.Parent.AsHeritageClause().Token == ast.KindImplementsKeyword) || - (decl.Kind == ast.KindInterfaceDeclaration && root.Parent.Parent.AsHeritageClause().Token == ast.KindExtendsKeyword) + if !isLastClause && root.Parent().Kind == ast.KindExpressionWithTypeArguments && root.Parent().Parent().Kind == ast.KindHeritageClause { + decl := root.Parent().Parent().Parent() + return (decl.Kind == ast.KindClassDeclaration && root.Parent().Parent().AsHeritageClause().Token == ast.KindImplementsKeyword) || + (decl.Kind == ast.KindInterfaceDeclaration && root.Parent().Parent().AsHeritageClause().Token == ast.KindExtendsKeyword) } return false @@ -244,7 +244,7 @@ func isThis(node *ast.Node) bool { return true case ast.KindIdentifier: // 'this' as a parameter - return node.Text() == "this" && node.Parent.Kind == ast.KindParameter + return node.Text() == "this" && node.Parent().Kind == ast.KindParameter default: return false } @@ -252,7 +252,7 @@ func isThis(node *ast.Node) bool { func isTypeReference(node *ast.Node) bool { if ast.IsRightSideOfQualifiedNameOrPropertyAccess(node) { - node = node.Parent + node = node.Parent() } switch node.Kind { @@ -262,27 +262,27 @@ func isTypeReference(node *ast.Node) bool { return true } - switch node.Parent.Kind { + switch node.Parent().Kind { case ast.KindTypeReference: return true case ast.KindImportType: - return !node.Parent.AsImportTypeNode().IsTypeOf + return !node.Parent().AsImportTypeNode().IsTypeOf case ast.KindExpressionWithTypeArguments: - return ast.IsPartOfTypeNode(node.Parent) + return ast.IsPartOfTypeNode(node.Parent()) } return false } func isInRightSideOfInternalImportEqualsDeclaration(node *ast.Node) bool { - if node.Parent == nil { + if node.Parent() == nil { return false } - for node.Parent.Kind == ast.KindQualifiedName { - node = node.Parent + for node.Parent().Kind == ast.KindQualifiedName { + node = node.Parent() } - return ast.IsInternalModuleImportEqualsDeclaration(node.Parent) && node.Parent.AsImportEqualsDeclaration().ModuleReference == node + return ast.IsInternalModuleImportEqualsDeclaration(node.Parent()) && node.Parent().AsImportEqualsDeclaration().ModuleReference() == node } func (l *LanguageService) createLspRangeFromNode(node *ast.Node, file *ast.SourceFile) (lsproto.Range, spanmap.Fidelity) { @@ -347,12 +347,12 @@ func isTypeKeyword(kind ast.Kind) bool { } func isSeparator(node *ast.Node, candidate *ast.Node) bool { - return candidate != nil && node.Parent != nil && (candidate.Kind == ast.KindCommaToken || (candidate.Kind == ast.KindSemicolonToken && node.Parent.Kind == ast.KindObjectLiteralExpression)) + return candidate != nil && node.Parent() != nil && (candidate.Kind == ast.KindCommaToken || (candidate.Kind == ast.KindSemicolonToken && node.Parent().Kind == ast.KindObjectLiteralExpression)) } func isLiteralNameOfPropertyDeclarationOrIndexAccess(node *ast.Node) bool { // utilities - switch node.Parent.Kind { + switch node.Parent().Kind { case ast.KindPropertyDeclaration, ast.KindPropertySignature, ast.KindPropertyAssignment, @@ -362,13 +362,13 @@ func isLiteralNameOfPropertyDeclarationOrIndexAccess(node *ast.Node) bool { ast.KindGetAccessor, ast.KindSetAccessor, ast.KindModuleDeclaration: - return ast.GetNameOfDeclaration(node.Parent) == node + return ast.GetNameOfDeclaration(node.Parent()) == node case ast.KindElementAccessExpression: - return node.Parent.AsElementAccessExpression().ArgumentExpression == node + return node.Parent().AsElementAccessExpression().ArgumentExpression() == node case ast.KindComputedPropertyName: return true case ast.KindLiteralType: - return node.Parent.Parent.Kind == ast.KindIndexedAccessType + return node.Parent().Parent().Kind == ast.KindIndexedAccessType default: return false } @@ -376,13 +376,13 @@ func isLiteralNameOfPropertyDeclarationOrIndexAccess(node *ast.Node) bool { func isObjectBindingElementWithoutPropertyName(bindingElement *ast.Node) bool { return bindingElement.Kind == ast.KindBindingElement && - bindingElement.Parent.Kind == ast.KindObjectBindingPattern && + bindingElement.Parent().Kind == ast.KindObjectBindingPattern && bindingElement.Name().Kind == ast.KindIdentifier && bindingElement.PropertyName() == nil } func isRightSideOfPropertyAccess(node *ast.Node) bool { - return node.Parent != nil && node.Parent.Kind == ast.KindPropertyAccessExpression && node.Parent.Name() == node + return node.Parent() != nil && node.Parent().Kind == ast.KindPropertyAccessExpression && node.Parent().Name() == node } func isStaticSymbol(symbol *ast.Symbol) bool { @@ -418,15 +418,15 @@ func isImplementationExpression(node *ast.Node) bool { } func isReadonlyTypeOperator(node *ast.Node) bool { - return node.Kind == ast.KindReadonlyKeyword && node.Parent.Kind == ast.KindTypeOperator && node.Parent.AsTypeOperatorNode().Operator == ast.KindReadonlyKeyword + return node.Kind == ast.KindReadonlyKeyword && node.Parent().Kind == ast.KindTypeOperator && node.Parent().AsTypeOperatorNode().Operator == ast.KindReadonlyKeyword } func isJumpStatementTarget(node *ast.Node) bool { - return node.Kind == ast.KindIdentifier && ast.IsBreakOrContinueStatement(node.Parent) && node.Parent.Label() == node + return node.Kind == ast.KindIdentifier && ast.IsBreakOrContinueStatement(node.Parent()) && node.Parent().Label() == node } func isLabelOfLabeledStatement(node *ast.Node) bool { - return node.Kind == ast.KindIdentifier && node.Parent.Kind == ast.KindLabeledStatement && node.Parent.Label() == node + return node.Kind == ast.KindIdentifier && node.Parent().Kind == ast.KindLabeledStatement && node.Parent().Label() == node } func findReferenceInPosition(refs []*ast.FileReference, pos int) *ast.FileReference { @@ -435,18 +435,18 @@ func findReferenceInPosition(refs []*ast.FileReference, pos int) *ast.FileRefere func getContainingNodeIfInHeritageClause(node *ast.Node) *ast.Node { if node.Kind == ast.KindIdentifier || node.Kind == ast.KindQualifiedName || node.Kind == ast.KindPropertyAccessExpression { - return getContainingNodeIfInHeritageClause(node.Parent) + return getContainingNodeIfInHeritageClause(node.Parent()) } if (node.Kind == ast.KindExpressionWithTypeArguments || node.Kind == ast.KindTypeReference) && - ast.IsHeritageClause(node.Parent) && - (ast.IsClassLike(node.Parent.Parent) || node.Parent.Parent.Kind == ast.KindInterfaceDeclaration) { - return node.Parent.Parent + ast.IsHeritageClause(node.Parent()) && + (ast.IsClassLike(node.Parent().Parent()) || node.Parent().Parent().Kind == ast.KindInterfaceDeclaration) { + return node.Parent().Parent() } return nil } func getContainerNode(node *ast.Node) *ast.Node { - for parent := node.Parent; parent != nil; parent = parent.Parent { + for parent := node.Parent(); parent != nil; parent = parent.Parent() { switch parent.Kind { case ast.KindSourceFile, ast.KindMethodDeclaration, ast.KindMethodSignature, ast.KindFunctionDeclaration, ast.KindFunctionExpression, ast.KindGetAccessor, ast.KindSetAccessor, ast.KindClassDeclaration, ast.KindInterfaceDeclaration, ast.KindEnumDeclaration, ast.KindModuleDeclaration: @@ -459,7 +459,7 @@ func getContainerNode(node *ast.Node) *ast.Node { func getAdjustedLocation(node *ast.Node, forRename bool, sourceFile *ast.SourceFile) *ast.Node { // todo: check if this function needs to be changed for jsdoc updates - parent := node.Parent + parent := node.Parent() // /**/ [|name|] ... // /**/ [|name|] ... // /**/ [|name|] ... @@ -504,8 +504,8 @@ func getAdjustedLocation(node *ast.Node, forRename bool, sourceFile *ast.SourceF // /**/ [|name|] ... if (node.Kind == ast.KindVarKeyword || node.Kind == ast.KindConstKeyword || node.Kind == ast.KindLetKeyword) && - ast.IsVariableDeclarationList(parent) && len(parent.AsVariableDeclarationList().Declarations.Nodes) == 1 { - declaration := parent.AsVariableDeclarationList().Declarations.Nodes[0].AsVariableDeclaration() + ast.IsVariableDeclarationList(parent) && len(parent.AsVariableDeclarationList().Declarations().Nodes) == 1 { + declaration := parent.AsVariableDeclarationList().Declarations().Nodes[0].AsVariableDeclaration() if ast.IsIdentifier(declaration.Name()) { return declaration.Name() } @@ -517,7 +517,7 @@ func getAdjustedLocation(node *ast.Node, forRename bool, sourceFile *ast.SourceF // import /**/type { propertyName as [|name|] } from ...; // import /**/type ... from "[|module|]"; if ast.IsImportClause(parent) && parent.IsTypeOnly() { - if location := getAdjustedLocationForImportDeclaration(parent.Parent.AsImportDeclaration(), forRename); location != nil { + if location := getAdjustedLocationForImportDeclaration(parent.Parent().AsImportDeclaration(), forRename); location != nil { return location } } @@ -544,7 +544,7 @@ func getAdjustedLocation(node *ast.Node, forRename bool, sourceFile *ast.SourceF return parent.Name() } if parent.Kind == ast.KindExportDeclaration { - if exportClause := parent.AsExportDeclaration().ExportClause; exportClause != nil && exportClause.Kind == ast.KindNamespaceExport { + if exportClause := parent.AsExportDeclaration().ExportClause(); exportClause != nil && exportClause.Kind == ast.KindNamespaceExport { return exportClause.Name() } } @@ -598,8 +598,8 @@ func getAdjustedLocation(node *ast.Node, forRename bool, sourceFile *ast.SourceF getAdjustedLocationForHeritageClause := func(node *ast.HeritageClause) *ast.Node { // /**/extends [|name|] // /**/implements [|name|] - if len(node.Types.Nodes) == 1 { - return ast.GetHeritageClauseElementName(node.Types.Nodes[0]) + if len(node.Types().Nodes) == 1 { + return ast.GetHeritageClauseElementName(node.Types().Nodes[0]) } // fall through `getAdjustedLocation` @@ -615,35 +615,35 @@ func getAdjustedLocation(node *ast.Node, forRename bool, sourceFile *ast.SourceF if node.Kind == ast.KindExtendsKeyword { // ... ... if parent.Kind == ast.KindTypeParameter { - if constraint := parent.AsTypeParameterDeclaration().Constraint; constraint != nil && constraint.Kind == ast.KindTypeReference { - return constraint.AsTypeReferenceNode().TypeName + if constraint := parent.AsTypeParameterDeclaration().Constraint(); constraint != nil && constraint.Kind == ast.KindTypeReference { + return constraint.AsTypeReferenceNode().TypeName() } } // ... T /**/extends [|U|] ? ... if parent.Kind == ast.KindConditionalType { - if extendsType := parent.AsConditionalTypeNode().ExtendsType; extendsType != nil && extendsType.Kind == ast.KindTypeReference { - return extendsType.AsTypeReferenceNode().TypeName + if extendsType := parent.AsConditionalTypeNode().ExtendsType(); extendsType != nil && extendsType.Kind == ast.KindTypeReference { + return extendsType.AsTypeReferenceNode().TypeName() } } } // ... T extends /**/infer [|U|] ? ... if node.Kind == ast.KindInferKeyword && parent.Kind == ast.KindInferType { - return parent.AsInferTypeNode().TypeParameter.Name() + return parent.AsInferTypeNode().TypeParameter().Name() } // { [ [|K|] /**/in keyof T]: ... } - if node.Kind == ast.KindInKeyword && parent.Kind == ast.KindTypeParameter && parent.Parent.Kind == ast.KindMappedType { + if node.Kind == ast.KindInKeyword && parent.Kind == ast.KindTypeParameter && parent.Parent().Kind == ast.KindMappedType { return parent.Name() } // /**/keyof [|T|] if node.Kind == ast.KindKeyOfKeyword && parent.Kind == ast.KindTypeOperator && parent.AsTypeOperatorNode().Operator == ast.KindKeyOfKeyword { if parentType := parent.Type(); parentType != nil && parentType.Kind == ast.KindTypeReference { - return parentType.AsTypeReferenceNode().TypeName + return parentType.AsTypeReferenceNode().TypeName() } } // /**/readonly [|name|][] if node.Kind == ast.KindReadonlyKeyword && parent.Kind == ast.KindTypeOperator && parent.AsTypeOperatorNode().Operator == ast.KindReadonlyKeyword { - if parentType := parent.Type(); parentType != nil && parentType.Kind == ast.KindArrayType && parentType.AsArrayTypeNode().ElementType.Kind == ast.KindTypeReference { - return parentType.AsArrayTypeNode().ElementType.AsTypeReferenceNode().TypeName + if parentType := parent.Type(); parentType != nil && parentType.Kind == ast.KindArrayType && parentType.AsArrayTypeNode().ElementType().Kind == ast.KindTypeReference { + return parentType.AsArrayTypeNode().ElementType().AsTypeReferenceNode().TypeName() } } @@ -671,14 +671,14 @@ func getAdjustedLocation(node *ast.Node, forRename bool, sourceFile *ast.SourceF // left /**/in [|name|] // left /**/instanceof [|name|] - if (node.Kind == ast.KindInKeyword || node.Kind == ast.KindInstanceOfKeyword) && parent.Kind == ast.KindBinaryExpression && parent.AsBinaryExpression().OperatorToken == node { - return ast.SkipOuterExpressions(parent.AsBinaryExpression().Right, ast.OEKAll) + if (node.Kind == ast.KindInKeyword || node.Kind == ast.KindInstanceOfKeyword) && parent.Kind == ast.KindBinaryExpression && parent.AsBinaryExpression().OperatorToken() == node { + return ast.SkipOuterExpressions(parent.AsBinaryExpression().Right(), ast.OEKAll) } // left /**/as [|name|] if node.Kind == ast.KindAsKeyword && parent.Kind == ast.KindAsExpression { if asExprType := parent.Type(); asExprType != nil && asExprType.Kind == ast.KindTypeReference { - return asExprType.AsTypeReferenceNode().TypeName + return asExprType.AsTypeReferenceNode().TypeName() } } @@ -718,15 +718,15 @@ func getAdjustedLocationForDeclaration(node *ast.Node, forRename bool, sourceFil } func getAdjustedLocationForImportDeclaration(node *ast.ImportDeclaration, forRename bool) *ast.Node { - if node.ImportClause != nil { - if name := node.ImportClause.Name(); name != nil { - if node.ImportClause.AsImportClause().NamedBindings != nil { + if node.ImportClause() != nil { + if name := node.ImportClause().Name(); name != nil { + if node.ImportClause().AsImportClause().NamedBindings() != nil { // do not adjust if we have both a name and named bindings return nil } // /**/import [|name|] from ...; // import /**/type [|name|] from ...; - return node.ImportClause.Name() + return node.ImportClause().Name() } // /**/import { [|name|] } from ...; @@ -735,7 +735,7 @@ func getAdjustedLocationForImportDeclaration(node *ast.ImportDeclaration, forRen // import /**/type { [|name|] } from ...; // import /**/type { propertyName as [|name|] } from ...; // import /**/type * as [|name|] from ...; - if namedBindings := node.ImportClause.AsImportClause().NamedBindings; namedBindings != nil { + if namedBindings := node.ImportClause().AsImportClause().NamedBindings(); namedBindings != nil { switch namedBindings.Kind { case ast.KindNamedImports: // do nothing if there is more than one binding @@ -755,35 +755,35 @@ func getAdjustedLocationForImportDeclaration(node *ast.ImportDeclaration, forRen // /**/import "[|module|]"; // /**/import ... from "[|module|]"; // import /**/type ... from "[|module|]"; - return node.ModuleSpecifier + return node.ModuleSpecifier() } return nil } func getAdjustedLocationForExportDeclaration(node *ast.ExportDeclaration, forRename bool) *ast.Node { - if node.ExportClause != nil { + if node.ExportClause() != nil { // /**/export { [|name|] } ... // /**/export { propertyName as [|name|] } ... // /**/export * as [|name|] ... // export /**/type { [|name|] } from ... // export /**/type { propertyName as [|name|] } from ... // export /**/type * as [|name|] ... - switch node.ExportClause.Kind { + switch node.ExportClause().Kind { case ast.KindNamedExports: // do nothing if there is more than one binding - elements := node.ExportClause.Elements() + elements := node.ExportClause().Elements() if len(elements) != 1 { return nil } return elements[0].Name() case ast.KindNamespaceExport: - return node.ExportClause.Name() + return node.ExportClause().Name() } } if !forRename { // /**/export * from "[|module|]"; // export /**/type * from "[|module|]"; - return node.ModuleSpecifier + return node.ModuleSpecifier() } return nil } @@ -807,7 +807,7 @@ func symbolFlagsHaveMeaning(flags ast.SymbolFlags, meaning ast.SemanticMeaning) func getMeaningFromLocation(node *ast.Node) ast.SemanticMeaning { // todo: check if this function needs to be changed for jsdoc updates node = getAdjustedLocation(ast.GetReparsedNodeForNode(node), false /*forRename*/, nil) - parent := node.Parent + parent := node.Parent() switch { case ast.IsSourceFile(node): return ast.SemanticMeaningValue @@ -819,9 +819,9 @@ func getMeaningFromLocation(node *ast.Node) ast.SemanticMeaning { // import a = |b.c|.d; // Namespace name := node if node.Kind != ast.KindQualifiedName { - name = core.IfElse(node.Parent.Kind == ast.KindQualifiedName && node.Parent.AsQualifiedName().Right == node, node.Parent, nil) + name = core.IfElse(node.Parent().Kind == ast.KindQualifiedName && node.Parent().AsQualifiedName().Right() == node, node.Parent(), nil) } - if name != nil && name.Parent.Kind == ast.KindImportEqualsDeclaration { + if name != nil && name.Parent().Kind == ast.KindImportEqualsDeclaration { return ast.SemanticMeaningAll } return ast.SemanticMeaningNamespace @@ -936,7 +936,7 @@ func getParentSymbolsOfPropertyAccess(location *ast.Node, symbol *ast.Symbol, ch if !isRightSideOfPropertyAccess(location) { return nil } - lhsType := ch.GetTypeAtLocation(location.Parent.Expression()) + lhsType := ch.GetTypeAtLocation(location.Parent().Expression()) if lhsType == nil { return nil } @@ -994,7 +994,7 @@ func getPropertySymbolsFromBaseTypes(symbol *ast.Symbol, propertyName string, ch } func getPropertySymbolFromBindingElement(checker *checker.Checker, bindingElement *ast.Node) *ast.Symbol { - if typeOfPattern := checker.GetTypeAtLocation(bindingElement.Parent); typeOfPattern != nil { + if typeOfPattern := checker.GetTypeAtLocation(bindingElement.Parent()); typeOfPattern != nil { return checker.GetPropertyOfType(typeOfPattern, bindingElement.Name().Text()) } return nil @@ -1014,7 +1014,7 @@ func getTargetLabel(referenceNode *ast.Node, labelName string) *ast.Node { if referenceNode.Kind == ast.KindLabeledStatement && referenceNode.Label().Text() == labelName { return referenceNode.Label() } - referenceNode = referenceNode.Parent + referenceNode = referenceNode.Parent() } return nil } @@ -1112,11 +1112,11 @@ func startEndContainsRange(start int, end int, textRange core.TextRange) bool { func getPossibleGenericSignatures(called *ast.Expression, typeArgumentCount int, c *checker.Checker) []*checker.Signature { typeAtLocation := c.GetTypeAtLocation(called) - if ast.IsOptionalChain(called.Parent) { - typeAtLocation = removeOptionality(typeAtLocation, ast.IsOptionalChainRoot(called.Parent), true /*isOptionalChain*/, c) + if ast.IsOptionalChain(called.Parent()) { + typeAtLocation = removeOptionality(typeAtLocation, ast.IsOptionalChainRoot(called.Parent()), true /*isOptionalChain*/, c) } var signatures []*checker.Signature - if ast.IsNewExpression(called.Parent) { + if ast.IsNewExpression(called.Parent()) { signatures = c.GetSignaturesOfType(typeAtLocation, checker.SignatureKindConstruct) } else { signatures = c.GetSignaturesOfType(typeAtLocation, checker.SignatureKindCall) @@ -1205,7 +1205,7 @@ func findContainingList(node *ast.Node, file *ast.SourceFile) *ast.NodeList { } return nodes } - astnav.VisitEachChildAndJSDoc(node.Parent, file, visitNode, visitNodes) + astnav.VisitEachChildAndJSDoc(node.Parent(), file, visitNode, visitNodes) return list } @@ -1260,7 +1260,7 @@ func getChildrenFromNonJSDocNode(node *ast.Node, sourceFile *ast.SourceFile) []* // Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 } func getContainingObjectLiteralElement(node *ast.Node) *ast.Node { element := getContainingObjectLiteralElementWorker(node) - if element != nil && (ast.IsObjectLiteralExpression(element.Parent) || ast.IsJsxAttributes(element.Parent)) { + if element != nil && (ast.IsObjectLiteralExpression(element.Parent()) || ast.IsJsxAttributes(element.Parent())) { return element } return nil @@ -1269,16 +1269,16 @@ func getContainingObjectLiteralElement(node *ast.Node) *ast.Node { func getContainingObjectLiteralElementWorker(node *ast.Node) *ast.Node { switch node.Kind { case ast.KindStringLiteral, ast.KindNoSubstitutionTemplateLiteral, ast.KindNumericLiteral: - if node.Parent.Kind == ast.KindComputedPropertyName { - if isObjectLiteralOrJsxElement(node.Parent.Parent) { - return node.Parent.Parent + if node.Parent().Kind == ast.KindComputedPropertyName { + if isObjectLiteralOrJsxElement(node.Parent().Parent()) { + return node.Parent().Parent() } return nil } fallthrough case ast.KindIdentifier, ast.KindJsxNamespacedName: - if isObjectLiteralOrJsxElement(node.Parent) && (node.Parent.Parent.Kind == ast.KindObjectLiteralExpression || node.Parent.Parent.Kind == ast.KindJsxAttributes) && node.Parent.Name() == node { - return node.Parent + if isObjectLiteralOrJsxElement(node.Parent()) && (node.Parent().Parent().Kind == ast.KindObjectLiteralExpression || node.Parent().Parent().Kind == ast.KindJsxAttributes) && node.Parent().Name() == node { + return node.Parent() } } return nil @@ -1360,14 +1360,14 @@ func getReferenceAtPosition(sourceFile *ast.SourceFile, position int, program *c } func getContextualTypeFromParent(node *ast.Expression, typeChecker *checker.Checker, contextFlags checker.ContextFlags) *checker.Type { - parent := ast.WalkUpParenthesizedExpressions(node.Parent) + parent := ast.WalkUpParenthesizedExpressions(node.Parent()) switch parent.Kind { case ast.KindNewExpression: return typeChecker.GetContextualType(parent, contextFlags) case ast.KindBinaryExpression: - if isEqualityOperatorKind(parent.AsBinaryExpression().OperatorToken.Kind) { + if isEqualityOperatorKind(parent.AsBinaryExpression().OperatorToken().Kind) { return typeChecker.GetTypeAtLocation( - core.IfElse(node == parent.AsBinaryExpression().Right, parent.AsBinaryExpression().Left, parent.AsBinaryExpression().Right), + core.IfElse(node == parent.AsBinaryExpression().Right(), parent.AsBinaryExpression().Left(), parent.AsBinaryExpression().Right()), ) } return typeChecker.GetContextualType(node, contextFlags) @@ -1401,7 +1401,7 @@ func getAncestorTypeNode(node *ast.Node) *ast.Node { if ast.IsTypeNode(n) { lastTypeNode = n } - return !ast.IsQualifiedName(n.Parent) && !ast.IsTypeNode(n.Parent) && !ast.IsTypeElement(n.Parent) + return !ast.IsQualifiedName(n.Parent()) && !ast.IsTypeNode(n.Parent()) && !ast.IsTypeElement(n.Parent()) }) return lastTypeNode } diff --git a/tsc/internal/modulespecifiers/specifiers.go b/tsc/internal/modulespecifiers/specifiers.go index 22a8102c0642a..6d16cfc67cbca 100644 --- a/tsc/internal/modulespecifiers/specifiers.go +++ b/tsc/internal/modulespecifiers/specifiers.go @@ -132,7 +132,7 @@ func tryGetModuleNameFromAmbientModule(moduleSymbol *ast.Symbol, checker Checker } possibleContainer := ast.FindAncestor(d, ast.IsModuleWithStringLiteralName) - if possibleContainer == nil || possibleContainer.Parent == nil || !ast.IsSourceFile(possibleContainer.Parent) { + if possibleContainer == nil || possibleContainer.Parent() == nil || !ast.IsSourceFile(possibleContainer.Parent()) { continue } diff --git a/tsc/internal/parser/jsdoc.go b/tsc/internal/parser/jsdoc.go index 6d239d2f228fc..52adeecbd8e8a 100644 --- a/tsc/internal/parser/jsdoc.go +++ b/tsc/internal/parser/jsdoc.go @@ -20,6 +20,7 @@ func parseJSDocForNode(sourceFile *ast.SourceFile, node *ast.Node) []*ast.Node { p := getParser() defer putParser(p) p.initializeState(sourceFile.ParseOptions(), sourceFile.Text(), sourceFile.ScriptKind) + p.factory.StartLazyJSDocParse(sourceFile) ranges := GetJSDocCommentRanges(&p.factory, nil, node, sourceFile.Text()) if len(ranges) == 0 { return nil @@ -28,7 +29,7 @@ func parseJSDocForNode(sourceFile *ast.SourceFile, node *ast.Node) []*ast.Node { pos := node.Pos() for _, comment := range ranges { if parsed := p.parseJSDocComment(node, comment.Pos(), comment.End(), pos); parsed != nil { - parsed.Parent = node + parsed.SetParent(node) jsdoc = append(jsdoc, parsed) pos = parsed.End() } @@ -82,7 +83,7 @@ func (p *Parser) withJSDoc(node *ast.Node, info jsdocScannerInfo) []*ast.Node { pos := node.Pos() for _, comment := range ranges { if parsed := p.parseJSDocComment(node, comment.Pos(), comment.End(), pos); parsed != nil { - parsed.Parent = node + parsed.SetParent(node) jsdoc = append(jsdoc, parsed) pos = parsed.End() } @@ -820,11 +821,11 @@ func isObjectOrObjectArrayTypeReference(node *ast.TypeNode) bool { case ast.KindObjectKeyword: return true case ast.KindArrayType: - return isObjectOrObjectArrayTypeReference(node.AsArrayTypeNode().ElementType) + return isObjectOrObjectArrayTypeReference(node.AsArrayTypeNode().ElementType()) default: if ast.IsTypeReferenceNode(node) { ref := node.AsTypeReferenceNode() - return ast.IsIdentifier(ref.TypeName) && ref.TypeName.Text() == "Object" && ref.TypeArguments == nil + return ast.IsIdentifier(ref.TypeName()) && ref.TypeName().Text() == "Object" && ref.TypeArguments() == nil } return false } @@ -1059,8 +1060,8 @@ func (p *Parser) parseTypedefTag(start int, tagName *ast.IdentifierNode, indent if hasChildren { isArrayType := typeExpression != nil && typeExpression.Type().Kind == ast.KindArrayType jsdocTypeLiteral := p.factory.NewJSDocTypeLiteral(jsdocPropertyTags, isArrayType) - if childTypeTag != nil && childTypeTag.TypeExpression != nil && !isObjectOrObjectArrayTypeReference(childTypeTag.TypeExpression.Type()) { - typeExpression = childTypeTag.TypeExpression + if childTypeTag != nil && childTypeTag.TypeExpression() != nil && !isObjectOrObjectArrayTypeReference(childTypeTag.TypeExpression().Type()) { + typeExpression = childTypeTag.TypeExpression() } else { // !!! This differs from Strada but prevents a crash pos := start @@ -1094,7 +1095,7 @@ func (p *Parser) parseTypedefTag(start int, tagName *ast.IdentifierNode, indent typedefTag := p.finishNodeWithEnd(p.factory.NewJSDocTypedefTag(tagName, typeExpression, fullName, comment), start, end) if typeExpression != nil { - typeExpression.Parent = typedefTag // forcibly overwrite parent potentially set by inner type expression parse + typeExpression.SetParent(typedefTag) // forcibly overwrite parent potentially set by inner type expression parse } return typedefTag } @@ -1173,9 +1174,9 @@ func (p *Parser) parseOverloadTag(start int, tagName *ast.IdentifierNode, indent func textsEqual(a *ast.EntityName, b *ast.EntityName) bool { for !ast.IsIdentifier(a) || !ast.IsIdentifier(b) { - if !ast.IsIdentifier(a) && !ast.IsIdentifier(b) && a.AsQualifiedName().Right.Text() == b.AsQualifiedName().Right.Text() { - a = a.AsQualifiedName().Left - b = b.AsQualifiedName().Left + if !ast.IsIdentifier(a) && !ast.IsIdentifier(b) && a.AsQualifiedName().Right().Text() == b.AsQualifiedName().Right().Text() { + a = a.AsQualifiedName().Left() + b = b.AsQualifiedName().Left() } else { return false } @@ -1197,7 +1198,7 @@ func (p *Parser) parseChildParameterOrPropertyTag(target propertyLikeParse, inde child := p.tryParseChildTag(target, indent) if child != nil && name != nil && (child.Kind == ast.KindJSDocParameterTag || child.Kind == ast.KindJSDocPropertyTag) && - (ast.IsIdentifier(child.Name()) || !textsEqual(name, child.Name().AsQualifiedName().Left)) { + (ast.IsIdentifier(child.Name()) || !textsEqual(name, child.Name().AsQualifiedName().Left())) { return nil } return child @@ -1278,16 +1279,18 @@ func (p *Parser) parseTemplateTagTypeParameter() *ast.Node { } func (p *Parser) parseTemplateTagTypeParameters() *ast.TypeParameterList { - typeParameters := ast.TypeParameterList{} + var nodes []*ast.Node for ok := true; ok; ok = p.parseOptionalJsdoc(ast.KindCommaToken) { // do-while loop p.skipWhitespace() node := p.parseTemplateTagTypeParameter() if node != nil { - typeParameters.Nodes = append(typeParameters.Nodes, node) + nodes = append(nodes, node) } p.skipWhitespaceOrAsterisk() } - return &typeParameters + typeParameters := p.factory.NewNodeList(p.nodeSliceArena.Clone(nodes)) + typeParameters.Loc = core.TextRange{} + return typeParameters } func (p *Parser) parseTemplateTag(start int, tagName *ast.IdentifierNode, indent int, indentText string) *ast.Node { diff --git a/tsc/internal/parser/parser.go b/tsc/internal/parser/parser.go index d969c8a98ef70..4275cff7e6fbd 100644 --- a/tsc/internal/parser/parser.go +++ b/tsc/internal/parser/parser.go @@ -85,7 +85,7 @@ type Parser struct { identifierCount int notParenthesizedArrow collections.Set[int] - nodeSliceArena core.Arena[*ast.Node] + nodeSliceArena nodeSliceArena stringSliceArena core.Arena[string] jsdocInfos []JSDocInfo possibleAwaitSpans []int @@ -135,16 +135,45 @@ func ParseSourceFile(opts ast.SourceFileParseOptions, sourceText string, scriptK p := getParser() defer putParser(p) p.initializeState(opts, sourceText, scriptKind) + p.factory.StartParse(sourceText) p.nextToken() + var result *ast.SourceFile if p.scriptKind == core.ScriptKindJSON { - return p.parseJSONText() + result = p.parseJSONText() + } else { + result = p.parseSourceFileWorker() + } + result.VerifyArena() + return result +} + +// nodeSliceArena allocates the element slices of node lists from the parser's node factory. +type nodeSliceArena struct { + factory *ast.NodeFactory +} + +func (a nodeSliceArena) NewSlice(size int) []*ast.Node { + return a.factory.NewNodeSlice(size) +} + +func (a nodeSliceArena) NewSlice1(node *ast.Node) []*ast.Node { + slice := a.NewSlice(1) + slice[0] = node + return slice +} + +func (a nodeSliceArena) Clone(nodes []*ast.Node) []*ast.Node { + if len(nodes) == 0 { + return nil } - return p.parseSourceFileWorker() + slice := a.NewSlice(len(nodes)) + copy(slice, nodes) + return slice } func (p *Parser) initializeClosures() { p.setParentFromContext = func(n *ast.Node) bool { - n.Parent = p.currentParent + n.SetParent(p.currentParent) return false } } @@ -244,7 +273,7 @@ func (p *Parser) validateJsonValue(sourceFile *ast.SourceFile, valueExpression * } return case ast.KindPrefixUnaryExpression: - if valueExpression.AsPrefixUnaryExpression().Operator != ast.KindMinusToken || valueExpression.AsPrefixUnaryExpression().Operand.Kind != ast.KindNumericLiteral { + if valueExpression.AsPrefixUnaryExpression().Operator != ast.KindMinusToken || valueExpression.AsPrefixUnaryExpression().Operand().Kind != ast.KindNumericLiteral { break // not valid JSON syntax } return @@ -266,7 +295,7 @@ func isDoubleQuotedString(node *ast.Node) bool { // validateJsonObjectLiteral validates properties of a JSON object literal. func (p *Parser) validateJsonObjectLiteral(sourceFile *ast.SourceFile, node *ast.ObjectLiteralExpression) { - for _, element := range node.Properties.Nodes { + for _, element := range node.Properties().Nodes { if element.Kind != ast.KindPropertyAssignment { p.diagnostics = append(p.diagnostics, ast.NewDiagnostic(sourceFile, getErrorSpanForNode(p.sourceText, element), diagnostics.Property_assignment_expected)) continue @@ -274,7 +303,7 @@ func (p *Parser) validateJsonObjectLiteral(sourceFile *ast.SourceFile, node *ast if element.Name() != nil && !isDoubleQuotedString(element.Name()) { p.diagnostics = append(p.diagnostics, ast.NewDiagnostic(sourceFile, getErrorSpanForNode(p.sourceText, element.Name()), diagnostics.String_literal_with_double_quotes_expected)) } - p.validateJsonValue(sourceFile, element.AsPropertyAssignment().Initializer) + p.validateJsonValue(sourceFile, element.AsPropertyAssignment().Initializer()) } } @@ -299,6 +328,7 @@ func (p *Parser) initializeState(opts ast.SourceFileParseOptions, sourceText str } p.opts = opts p.sourceText = sourceText + p.nodeSliceArena.factory = &p.factory p.scriptKind = scriptKind p.languageVariant = getLanguageVariant(p.scriptKind) switch p.scriptKind { @@ -604,7 +634,7 @@ func (p *Parser) reparseTopLevelAwait(sourceFile *ast.SourceFile) *ast.Node { result := p.factory.NewSourceFile(sourceFile.ParseOptions(), p.sourceText, p.newNodeList(sourceFile.Statements.Loc, statements), sourceFile.EndOfFileToken) for _, s := range statements { - s.Parent = result.AsNode() // force (re)set parent to reparsed source file + s.SetParent(result.AsNode()) // force (re)set parent to reparsed source file } return result } @@ -722,7 +752,7 @@ func (p *Parser) parseEmptyNodeList() *ast.NodeList { func (p *Parser) createMissingList() *ast.NodeList { result := p.parseEmptyNodeList() - result.Nodes = missingListNodes + result.SetNodes(missingListNodes) return result } @@ -1783,7 +1813,7 @@ func (p *Parser) parseClassDeclarationOrExpression(pos int, jsdoc jsdocScannerIn if heritageClauses != nil { for _, clause := range heritageClauses.Nodes { if clause.AsHeritageClause().Token == ast.KindExtendsKeyword { - for _, expr := range clause.AsHeritageClause().Types.Nodes { + for _, expr := range clause.AsHeritageClause().Types().Nodes { p.checkJSSyntax(expr) } } @@ -1851,11 +1881,11 @@ func isTypeHeritageClause(isInterface bool, token ast.Kind) bool { func (p *Parser) parseTypeHeritageClauseElement() *ast.HeritageClauseElement { pos := p.nodePos() expressionWithTypeArguments := p.parseExpressionWithTypeArguments().AsExpressionWithTypeArguments() - if !isValidHeritageTypeReferenceExpression(expressionWithTypeArguments.Expression) { + if !isValidHeritageTypeReferenceExpression(expressionWithTypeArguments.Expression()) { return expressionWithTypeArguments.AsNode() } - typeName := p.convertEntityNameExpressionToEntityName(expressionWithTypeArguments.Expression) - return p.finishNode(p.factory.NewTypeReferenceNode(typeName, expressionWithTypeArguments.TypeArguments), pos) + typeName := p.convertEntityNameExpressionToEntityName(expressionWithTypeArguments.Expression()) + return p.finishNode(p.factory.NewTypeReferenceNode(typeName, expressionWithTypeArguments.TypeArguments()), pos) } func isValidHeritageTypeReferenceExpression(node *ast.Node) bool { @@ -1874,7 +1904,7 @@ func (p *Parser) convertEntityNameExpressionToEntityName(node *ast.Node) *ast.No } propertyAccess := node.AsPropertyAccessExpression() result := p.factory.NewQualifiedName( - p.convertEntityNameExpressionToEntityName(propertyAccess.Expression), + p.convertEntityNameExpressionToEntityName(propertyAccess.Expression()), propertyAccess.Name(), ) return p.finishNodeWithEnd(result, node.Pos(), node.End()) @@ -2058,7 +2088,7 @@ func (p *Parser) parseErrorForMissingSemicolonAfter(node *ast.Node) { // module `M1` { // ^^^^^^^^^^^ This block is parsed as a template literal like module`M1`. if node.Kind == ast.KindTaggedTemplateExpression { - p.parseErrorAtRange(p.skipRangeTrivia(node.AsTaggedTemplateExpression().Template.Loc), diagnostics.Module_declaration_names_may_only_use_or_quoted_strings) + p.parseErrorAtRange(p.skipRangeTrivia(node.AsTaggedTemplateExpression().Template().Loc), diagnostics.Module_declaration_names_may_only_use_or_quoted_strings) return } // Otherwise, if this isn't a well-known keyword-like identifier, give the generic fallback message. @@ -3726,7 +3756,7 @@ func (p *Parser) parseTupleElementType() *ast.TypeNode { node := p.factory.NewOptionalTypeNode(typeNode.Type()) node.Flags = typeNode.Flags node.Loc = typeNode.Loc - typeNode.Type().Parent = node + typeNode.Type().SetParent(node) return node } return typeNode @@ -3785,7 +3815,7 @@ func (p *Parser) parseTemplateTypeSpans() *ast.NodeList { for { span := p.parseTemplateTypeSpan() list = append(list, span) - if span.AsTemplateLiteralTypeSpan().Literal.Kind != ast.KindTemplateMiddle { + if span.AsTemplateLiteralTypeSpan().Literal().Kind != ast.KindTemplateMiddle { break } } @@ -4524,9 +4554,9 @@ func (p *Parser) parseModifiersForArrowFunction() *ast.ModifierList { func typeHasArrowFunctionBlockingParseError(node *ast.TypeNode) bool { switch node.Kind { case ast.KindTypeReference: - return ast.NodeIsMissing(node.AsTypeReferenceNode().TypeName) + return ast.NodeIsMissing(node.AsTypeReferenceNode().TypeName()) case ast.KindFunctionType, ast.KindConstructorType: - return isMissingNodeList(node.FunctionLikeData().Parameters) || typeHasArrowFunctionBlockingParseError(node.Type()) + return isMissingNodeList(node.FunctionLikeData().Parameters()) || typeHasArrowFunctionBlockingParseError(node.Type()) case ast.KindParenthesizedType: return typeHasArrowFunctionBlockingParseError(node.Type()) } @@ -4709,7 +4739,7 @@ func (p *Parser) parseBinaryExpressionRest(precedence ast.OperatorPrecedence, le // assertion. See https://github.com/microsoft/TypeScript/issues/63527. lastPrecedence := ast.OperatorPrecedenceHighest if ast.IsBinaryExpression(lastOperand) { - lastPrecedence = ast.GetBinaryOperatorPrecedence(lastOperand.AsBinaryExpression().OperatorToken.Kind) + lastPrecedence = ast.GetBinaryOperatorPrecedence(lastOperand.AsBinaryExpression().OperatorToken().Kind) } if operator == ast.KindSatisfiesKeyword { leftOperand = p.makeSatisfiesExpression(leftOperand, p.parseType()) @@ -4821,8 +4851,8 @@ func (p *Parser) parseJsxElementOrSelfClosingElementOrFragment(inExpressionConte var closingElement *ast.Node lastChild := core.LastOrNil(children.Nodes) if lastChild != nil && lastChild.Kind == ast.KindJsxElement && - !ast.TagNamesAreEquivalent(lastChild.AsJsxElement().OpeningElement.TagName(), lastChild.AsJsxElement().ClosingElement.TagName()) && - ast.TagNamesAreEquivalent(opening.TagName(), lastChild.AsJsxElement().ClosingElement.TagName()) { + !ast.TagNamesAreEquivalent(lastChild.AsJsxElement().OpeningElement().TagName(), lastChild.AsJsxElement().ClosingElement().TagName()) && + ast.TagNamesAreEquivalent(opening.TagName(), lastChild.AsJsxElement().ClosingElement().TagName()) { // when an unclosed JsxOpeningElement incorrectly parses its parent's JsxClosingElement, // restructure (
(......
)) --> (
(......)
) // (no need to error; the parent will error) @@ -4830,22 +4860,22 @@ func (p *Parser) parseJsxElementOrSelfClosingElementOrFragment(inExpressionConte missingIdentifier := p.finishNodeWithEnd(p.newIdentifier(""), end, end) newClosingElement := p.finishNodeWithEnd(p.factory.NewJsxClosingElement(missingIdentifier), end, end) newLast := p.finishNodeWithEnd( - p.factory.NewJsxElement(lastChild.AsJsxElement().OpeningElement, lastChild.Children(), newClosingElement), - lastChild.AsJsxElement().OpeningElement.Pos(), + p.factory.NewJsxElement(lastChild.AsJsxElement().OpeningElement(), lastChild.Children(), newClosingElement), + lastChild.AsJsxElement().OpeningElement().Pos(), end, ) // force reset parent pointers from discarded parse result - if lastChild.AsJsxElement().OpeningElement != nil { - lastChild.AsJsxElement().OpeningElement.Parent = newLast + if lastChild.AsJsxElement().OpeningElement() != nil { + lastChild.AsJsxElement().OpeningElement().SetParent(newLast) } if lastChild.Children() != nil { for _, c := range lastChild.Children().Nodes { - c.Parent = newLast + c.SetParent(newLast) } } - newClosingElement.Parent = newLast + newClosingElement.SetParent(newLast) children = p.newNodeList(core.NewTextRange(children.Pos(), newLast.End()), append(children.Nodes[0:len(children.Nodes)-1], newLast)) - closingElement = lastChild.AsJsxElement().ClosingElement + closingElement = lastChild.AsJsxElement().ClosingElement() } else { closingElement = p.parseJsxClosingElement(opening, inExpressionContext) if !ast.TagNamesAreEquivalent(opening.TagName(), closingElement.TagName()) { @@ -4859,7 +4889,7 @@ func (p *Parser) parseJsxElementOrSelfClosingElementOrFragment(inExpressionConte } } result = p.finishNode(p.factory.NewJsxElement(opening, children, closingElement), pos) - closingElement.Parent = result // force reset parent pointers from possibly discarded parse result + closingElement.SetParent(result) // force reset parent pointers from possibly discarded parse result case ast.KindJsxOpeningFragment: result = p.finishNode(p.factory.NewJsxFragment(opening, p.parseJsxChildren(opening), p.parseJsxClosingFragment(inExpressionContext)), pos) case ast.KindJsxSelfClosingElement: @@ -4904,8 +4934,8 @@ func (p *Parser) parseJsxChildren(openingTag *ast.Expression) *ast.NodeList { } list = append(list, child) if ast.IsJsxOpeningElement(openingTag) && child.Kind == ast.KindJsxElement && - !ast.TagNamesAreEquivalent(child.AsJsxElement().OpeningElement.TagName(), child.AsJsxElement().ClosingElement.TagName()) && - ast.TagNamesAreEquivalent(openingTag.TagName(), child.AsJsxElement().ClosingElement.TagName()) { + !ast.TagNamesAreEquivalent(child.AsJsxElement().OpeningElement().TagName(), child.AsJsxElement().ClosingElement().TagName()) && + ast.TagNamesAreEquivalent(openingTag.TagName(), child.AsJsxElement().ClosingElement().TagName()) { // stop after parsing a mismatched child like
...(
) in order to reattach the
higher break } @@ -5452,8 +5482,8 @@ func (p *Parser) parseMemberExpressionRest(pos int, expression *ast.Expression, // Absorb type arguments into TemplateExpression when preceding expression is ExpressionWithTypeArguments if questionDotToken == nil && ast.IsExpressionWithTypeArguments(expression) { original := expression.AsExpressionWithTypeArguments() - expression = p.parseTaggedTemplateRest(pos, original.Expression, questionDotToken, original.TypeArguments) - p.unparseExpressionWithTypeArguments(original.Expression, original.TypeArguments, expression) + expression = p.parseTaggedTemplateRest(pos, original.Expression(), questionDotToken, original.TypeArguments()) + p.unparseExpressionWithTypeArguments(original.Expression(), original.TypeArguments(), expression) } else { expression = p.parseTaggedTemplateRest(pos, expression, questionDotToken, nil /*typeArguments*/) } @@ -5551,7 +5581,7 @@ func (p *Parser) parseCallExpressionRest(pos int, expression *ast.Expression) *a // Absorb type arguments into CallExpression when preceding expression is ExpressionWithTypeArguments if questionDotToken == nil && expression.Kind == ast.KindExpressionWithTypeArguments { typeArguments = expression.TypeArgumentList() - expression = expression.AsExpressionWithTypeArguments().Expression + expression = expression.AsExpressionWithTypeArguments().Expression() } inner := expression argumentList := p.parseArgumentList() @@ -5622,7 +5652,7 @@ func (p *Parser) parseTemplateSpans(isTaggedTemplate bool) *ast.NodeList { for { span := p.parseTemplateSpan(isTaggedTemplate) list = append(list, span) - if span.AsTemplateSpan().Literal.Kind != ast.KindTemplateMiddle { + if span.AsTemplateSpan().Literal().Kind != ast.KindTemplateMiddle { break } } @@ -5824,11 +5854,11 @@ func (p *Parser) parseDecoratedExpression() *ast.Expression { func (p *Parser) unparseExpressionWithTypeArguments(expression *ast.Node, typeArguments *ast.NodeList, result *ast.Node) { // force overwrite the `.Parent` of the expression and type arguments to erase the fact that they may have originally been parsed as an ExpressionWithTypeArguments and be parented to such if expression != nil { - expression.Parent = result + expression.SetParent(result) } if typeArguments != nil { for _, a := range typeArguments.Nodes { - a.Parent = result + a.SetParent(result) } } } @@ -5846,7 +5876,7 @@ func (p *Parser) parseNewExpressionOrNewDotTarget() *ast.Node { // Absorb type arguments into NewExpression when preceding expression is ExpressionWithTypeArguments if expression.Kind == ast.KindExpressionWithTypeArguments { typeArguments = expression.TypeArgumentList() - expression = expression.AsExpressionWithTypeArguments().Expression + expression = expression.AsExpressionWithTypeArguments().Expression() } if p.token == ast.KindQuestionDotToken { p.parseErrorAtCurrentToken(diagnostics.Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0, scanner.GetTextOfNodeFromSourceText(p.sourceText, expression, false /*includeTrivia*/)) diff --git a/tsc/internal/parser/parser_test.go b/tsc/internal/parser/parser_test.go index 8c68c97a462bd..3eae7b46dc4a2 100644 --- a/tsc/internal/parser/parser_test.go +++ b/tsc/internal/parser/parser_test.go @@ -172,20 +172,20 @@ class MissingImplements implements B. {} }, sourceText, core.ScriptKindTS) classDecl := file.Statements.Nodes[0].AsClassDeclaration() - assert.Equal(t, classDecl.HeritageClauses.Nodes[0].AsHeritageClause().Types.Nodes[0].Kind, ast.KindExpressionWithTypeArguments) - assert.Equal(t, classDecl.HeritageClauses.Nodes[1].AsHeritageClause().Types.Nodes[0].Kind, ast.KindTypeReference) + assert.Equal(t, classDecl.HeritageClauses().Nodes[0].AsHeritageClause().Types().Nodes[0].Kind, ast.KindExpressionWithTypeArguments) + assert.Equal(t, classDecl.HeritageClauses().Nodes[1].AsHeritageClause().Types().Nodes[0].Kind, ast.KindTypeReference) interfaceDecl := file.Statements.Nodes[1].AsInterfaceDeclaration() - assert.Equal(t, interfaceDecl.HeritageClauses.Nodes[0].AsHeritageClause().Types.Nodes[0].Kind, ast.KindTypeReference) + assert.Equal(t, interfaceDecl.HeritageClauses().Nodes[0].AsHeritageClause().Types().Nodes[0].Kind, ast.KindTypeReference) invalidInterfaceDecl := file.Statements.Nodes[2].AsInterfaceDeclaration() - assert.Equal(t, invalidInterfaceDecl.HeritageClauses.Nodes[0].AsHeritageClause().Types.Nodes[0].Kind, ast.KindExpressionWithTypeArguments) + assert.Equal(t, invalidInterfaceDecl.HeritageClauses().Nodes[0].AsHeritageClause().Types().Nodes[0].Kind, ast.KindExpressionWithTypeArguments) missingExtendsDecl := file.Statements.Nodes[3].AsInterfaceDeclaration() - assert.Equal(t, missingExtendsDecl.HeritageClauses.Nodes[0].AsHeritageClause().Types.Nodes[0].Kind, ast.KindExpressionWithTypeArguments) + assert.Equal(t, missingExtendsDecl.HeritageClauses().Nodes[0].AsHeritageClause().Types().Nodes[0].Kind, ast.KindExpressionWithTypeArguments) missingImplementsDecl := file.Statements.Nodes[4].AsClassDeclaration() - assert.Equal(t, missingImplementsDecl.HeritageClauses.Nodes[0].AsHeritageClause().Types.Nodes[0].Kind, ast.KindExpressionWithTypeArguments) + assert.Equal(t, missingImplementsDecl.HeritageClauses().Nodes[0].AsHeritageClause().Types().Nodes[0].Kind, ast.KindExpressionWithTypeArguments) } func TestParseStaticSourcePhaseImport(t *testing.T) { @@ -253,13 +253,13 @@ func TestParseStaticSourcePhaseImport(t *testing.T) { assert.Assert(t, ast.IsImportDeclaration(statement)) declaration := statement.AsImportDeclaration() - assert.Assert(t, declaration.ImportClause != nil) + assert.Assert(t, declaration.ImportClause() != nil) - clause := declaration.ImportClause.AsImportClause() + clause := declaration.ImportClause().AsImportClause() assert.Equal(t, clause.PhaseModifier, test.phaseModifier) assert.Assert(t, clause.Name() != nil) assert.Equal(t, clause.Name().Text(), test.bindingName) - assert.Equal(t, declaration.Attributes != nil, test.hasAttributes) + assert.Equal(t, declaration.Attributes() != nil, test.hasAttributes) }) } } @@ -298,12 +298,12 @@ func TestParseInvalidStaticSourcePhaseImports(t *testing.T) { assert.Assert(t, ast.IsImportDeclaration(statement)) declaration := statement.AsImportDeclaration() - assert.Assert(t, declaration.ImportClause != nil) + assert.Assert(t, declaration.ImportClause() != nil) - clause := declaration.ImportClause.AsImportClause() + clause := declaration.ImportClause().AsImportClause() assert.Equal(t, clause.PhaseModifier, ast.KindSourceKeyword) assert.Equal(t, clause.Name() != nil, test.hasName) - assert.Equal(t, clause.NamedBindings != nil, test.hasNamedBindings) + assert.Equal(t, clause.NamedBindings() != nil, test.hasNamedBindings) } } @@ -316,7 +316,7 @@ func TestParseDynamicSourcePhaseImport(t *testing.T) { statement := file.Statements.Nodes[0] assert.Assert(t, ast.IsExpressionStatement(statement)) - call := statement.AsExpressionStatement().Expression + call := statement.AsExpressionStatement().Expression() assert.Assert(t, ast.IsCallExpression(call)) assert.Assert(t, ast.IsImportCall(call)) assert.Assert(t, call.SubtreeFacts()&ast.SubtreeContainsDynamicImport != 0) @@ -352,7 +352,7 @@ func TestParseEscapedDynamicImportPhase(t *testing.T) { statement := file.Statements.Nodes[0] assert.Assert(t, ast.IsExpressionStatement(statement)) - call := statement.AsExpressionStatement().Expression + call := statement.AsExpressionStatement().Expression() assert.Assert(t, ast.IsCallExpression(call)) assert.Assert(t, ast.IsImportCall(call)) @@ -438,10 +438,10 @@ const value = 0;` jsDocs := typeAlias.JSDoc(file) assert.Equal(t, len(jsDocs), 1) - assert.Assert(t, jsDocs[0].AsJSDoc().Tags != nil) - assert.Equal(t, len(jsDocs[0].AsJSDoc().Tags.Nodes), 1) + assert.Assert(t, jsDocs[0].AsJSDoc().Tags() != nil) + assert.Equal(t, len(jsDocs[0].AsJSDoc().Tags().Nodes), 1) - typeExpression := jsDocs[0].AsJSDoc().Tags.Nodes[0].TypeExpression() + typeExpression := jsDocs[0].AsJSDoc().Tags().Nodes[0].TypeExpression() assert.Assert(t, typeExpression != nil) expected := strings.Join([]string{"(", `"a" |`, `"b"`, ")[]"}, core.NewLineKindLF.GetNewLineCharacter()) diff --git a/tsc/internal/parser/reparser.go b/tsc/internal/parser/reparser.go index bdebd40ade98d..6e5f2080ee883 100644 --- a/tsc/internal/parser/reparser.go +++ b/tsc/internal/parser/reparser.go @@ -58,7 +58,7 @@ func (p *Parser) checkNonIdentifierName(name *ast.Node) *ast.Node { func (p *Parser) reparseTags(parent *ast.Node, jsDoc []*ast.Node) { for _, j := range jsDoc { isLast := j == jsDoc[len(jsDoc)-1] - tags := j.AsJSDoc().Tags + tags := j.AsJSDoc().Tags() if tags == nil { continue } @@ -85,7 +85,7 @@ func (p *Parser) reparseUnhosted(tag *ast.Node, parent *ast.Node, jsDoc *ast.Nod modifiers = p.createExportModifier(tag) } typeAlias := p.factory.NewJSTypeAliasDeclaration(modifiers, p.addDeepCloneReparse(p.checkNonIdentifierName(p.getInnermostNameOfJSDocNamespace(fullName))), nil, nil) - typeAlias.AsTypeAliasDeclaration().TypeParameters = p.gatherTypeParameters(jsDoc, true /*typedefOrCallback*/) + typeAlias.AsTypeAliasDeclaration().SetTypeParameters(p.gatherTypeParameters(jsDoc, true /*typedefOrCallback*/)) var t *ast.Node switch typeExpression.Kind { case ast.KindJSDocTypeExpression: @@ -95,7 +95,7 @@ func (p *Parser) reparseUnhosted(tag *ast.Node, parent *ast.Node, jsDoc *ast.Nod default: panic("typedef tag type expression should be a name reference or a type expression" + typeExpression.Kind.String()) } - typeAlias.AsTypeAliasDeclaration().Type = t + typeAlias.AsTypeAliasDeclaration().SetType(t) p.finishReparsedNode(typeAlias, tag) p.jsdocInfos = append(p.jsdocInfos, JSDocInfo{parent: typeAlias, jsDocs: []*ast.Node{jsDoc}}) typeAlias.Flags |= ast.NodeFlagsHasJSDoc @@ -114,7 +114,7 @@ func (p *Parser) reparseUnhosted(tag *ast.Node, parent *ast.Node, jsDoc *ast.Nod } functionType := p.reparseJSDocSignature(typeExpression, tag, jsDoc, tag, nil) typeAlias := p.factory.NewJSTypeAliasDeclaration(modifiers, p.addDeepCloneReparse(p.getInnermostNameOfJSDocNamespace(fullName)), nil, functionType) - typeAlias.AsTypeAliasDeclaration().TypeParameters = p.gatherTypeParameters(jsDoc, true /*typedefOrCallback*/) + typeAlias.AsTypeAliasDeclaration().SetTypeParameters(p.gatherTypeParameters(jsDoc, true /*typedefOrCallback*/)) p.finishReparsedNode(typeAlias, tag) p.jsdocInfos = append(p.jsdocInfos, JSDocInfo{parent: typeAlias, jsDocs: []*ast.Node{jsDoc}}) typeAlias.Flags |= ast.NodeFlagsHasJSDoc @@ -122,23 +122,23 @@ func (p *Parser) reparseUnhosted(tag *ast.Node, parent *ast.Node, jsDoc *ast.Nod p.reparseList = append(p.reparseList, result) case ast.KindJSDocImportTag: importTag := tag.AsJSDocImportTag() - if importTag.ImportClause == nil { + if importTag.ImportClause() == nil { break } - importClause := p.addDeepCloneReparse(importTag.ImportClause) + importClause := p.addDeepCloneReparse(importTag.ImportClause()) importClause.AsImportClause().PhaseModifier = ast.KindTypeKeyword importDeclaration := p.factory.NewJSImportDeclaration( p.factory.DeepCloneReparseModifiers(importTag.Modifiers()), importClause, - p.addDeepCloneReparse(importTag.ModuleSpecifier), - p.addDeepCloneReparse(importTag.Attributes), + p.addDeepCloneReparse(importTag.ModuleSpecifier()), + p.addDeepCloneReparse(importTag.Attributes()), ) p.finishReparsedNode(importDeclaration, tag) p.reparseList = append(p.reparseList, importDeclaration) case ast.KindJSDocOverloadTag: // Create overload signatures only for function, method, and constructor declarations outside object literals if (ast.IsFunctionDeclaration(parent) || ast.IsMethodDeclaration(parent) || ast.IsConstructorDeclaration(parent)) && p.parsingContexts&(1< 0 || - p.getClosingLineTerminatorCount(body.AsNode(), core.LastOrNil(body.Statements.Nodes), LFPreserveLines, body.Statements.Loc) > 0 { + if p.getLeadingLineTerminatorCount(body.AsNode(), core.FirstOrNil(body.Statements().Nodes), LFPreserveLines) > 0 || + p.getClosingLineTerminatorCount(body.AsNode(), core.LastOrNil(body.Statements().Nodes), LFPreserveLines, body.Statements().Loc) > 0 { return false } var previousStatement *ast.Statement - for _, statement := range body.Statements.Nodes { + for _, statement := range body.Statements().Nodes { if p.getSeparatingLineTerminatorCount(previousStatement, statement, LFPreserveLines) > 0 { return false } @@ -1209,16 +1209,16 @@ func (p *Printer) emitPrivateIdentifier(node *ast.PrivateIdentifier) { func (p *Printer) emitQualifiedName(node *ast.QualifiedName) { state := p.enterNode(node.AsNode()) - p.emitEntityName(node.Left) + p.emitEntityName(node.Left()) p.writePunctuation(".") - p.emitMemberName(node.Right) + p.emitMemberName(node.Right()) p.exitNode(node.AsNode(), state) } func (p *Printer) emitComputedPropertyName(node *ast.ComputedPropertyName) { state := p.enterNode(node.AsNode()) p.writePunctuation("[") - p.emitExpression(node.Expression, ast.OperatorPrecedenceDisallowComma) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceDisallowComma) p.writePunctuation("]") p.exitNode(node.AsNode(), state) } @@ -1445,17 +1445,17 @@ func (p *Printer) emitTypeParameter(node *ast.TypeParameterDeclaration) { state := p.enterNode(node.AsNode()) p.emitModifierList(node.AsNode(), node.Modifiers(), false /*allowDecorators*/) p.emitBindingIdentifier(node.Name().AsIdentifier()) - if node.Constraint != nil { + if node.Constraint() != nil { p.writeSpace() p.writeKeyword("extends") p.writeSpace() - p.emitTypeNodeOutsideExtends(node.Constraint) + p.emitTypeNodeOutsideExtends(node.Constraint()) } - if node.DefaultType != nil { + if node.DefaultType() != nil { p.writeSpace() p.writeOperator("=") p.writeSpace() - p.emitTypeNodeOutsideExtends(node.DefaultType) + p.emitTypeNodeOutsideExtends(node.DefaultType()) } p.exitNode(node.AsNode(), state) } @@ -1480,15 +1480,15 @@ func (p *Printer) emitParameterName(node *ast.BindingName) { func (p *Printer) emitParameter(node *ast.ParameterDeclaration) { state := p.enterNode(node.AsNode()) p.emitModifierList(node.AsNode(), node.Modifiers(), true /*allowDecorators*/) - p.emitTokenNode(node.DotDotDotToken) + p.emitTokenNode(node.DotDotDotToken()) p.emitParameterName(node.Name()) - p.emitTokenNode(node.QuestionToken) + p.emitTokenNode(node.QuestionToken()) - p.emitTypeAnnotation(node.Type) + p.emitTypeAnnotation(node.Type()) // The comment position has to fallback to any present node within the parameter declaration because as it turns // out, the parser can make parameter declarations with _just_ an initializer. - p.emitInitializer(node.Initializer, greatestEnd(node.Pos(), node.Type, node.QuestionToken, node.Name(), node.Modifiers()), node.AsNode()) + p.emitInitializer(node.Initializer(), greatestEnd(node.Pos(), node.Type(), node.QuestionToken(), node.Name(), node.Modifiers()), node.AsNode()) p.exitNode(node.AsNode(), state) } @@ -1499,7 +1499,7 @@ func (p *Printer) emitParameterDeclarationNode(node *ast.ParameterDeclarationNod func (p *Printer) emitDecorator(node *ast.Decorator) { state := p.enterNode(node.AsNode()) p.writePunctuation("@") - p.emitExpression(node.Expression, ast.OperatorPrecedenceLeftHandSide) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceLeftHandSide) p.exitNode(node.AsNode(), state) } @@ -1557,15 +1557,15 @@ func canEmitSimpleArrowHead(parentNode *ast.Node, parameters *ast.ParameterList) parameter := parameters.Nodes[0].AsParameterDeclaration() return parameter.Pos() == parent.Pos() && // may not have parsed tokens between start of parent and parameter - parent.TypeParameters == nil && // parent may not have type parameters - parent.Type == nil && // parent may not have return type annotation + parent.TypeParameters() == nil && // parent may not have type parameters + parent.Type() == nil && // parent may not have return type annotation (parent.Modifiers() == nil || len(parent.Modifiers().Nodes) == 0) && // parent may not have modifiers !parameters.HasTrailingComma() && // parameters may not have a trailing comma parameter.Modifiers() == nil && // parameter may not have decorators or modifiers - parameter.DotDotDotToken == nil && // parameter may not be rest - parameter.QuestionToken == nil && // parameter may not be optional - parameter.Type == nil && // parameter may not have a type annotation - parameter.Initializer == nil && // parameter may not have an initializer + parameter.DotDotDotToken() == nil && // parameter may not be rest + parameter.QuestionToken() == nil && // parameter may not be optional + parameter.Type() == nil && // parameter may not have a type annotation + parameter.Initializer() == nil && // parameter may not have an initializer ast.IsIdentifier(parameter.Name()) // parameter name must be identifier } @@ -1590,11 +1590,11 @@ func (p *Printer) emitSignature(node *ast.Node) { ////if n.TypeArguments != nil { //// p.emitTypeArguments(node, n.TypeArguments) ////} else { - p.emitTypeParameters(node, n.TypeParameters) + p.emitTypeParameters(node, n.TypeParameters()) ////} - p.emitParameters(node, n.Parameters) - p.emitTypeAnnotation(n.Type) + p.emitParameters(node, n.Parameters()) + p.emitTypeAnnotation(n.Type()) } func (p *Printer) emitFunctionBody(body *ast.Block) { @@ -1615,25 +1615,25 @@ func (p *Printer) emitFunctionBody(body *ast.Block) { p.writePunctuation("{") p.increaseIndent() - detachedState := p.emitDetachedCommentsBeforeStatementList(body.AsNode(), body.Statements.Loc) - statementOffset := p.emitPrologueDirectives(body.Statements) + detachedState := p.emitDetachedCommentsBeforeStatementList(body.AsNode(), body.Statements().Loc) + statementOffset := p.emitPrologueDirectives(body.Statements()) pos := p.writer.GetTextPos() p.emitHelpers(body.AsNode()) if p.shouldEmitBlockFunctionBodyOnSingleLine(body) && statementOffset == 0 && pos == p.writer.GetTextPos() { p.decreaseIndent() - p.emitListRange((*Printer).emitStatement, body.AsNode(), body.Statements, LFSingleLineFunctionBodyStatements, statementOffset, -1) + p.emitListRange((*Printer).emitStatement, body.AsNode(), body.Statements(), LFSingleLineFunctionBodyStatements, statementOffset, -1) p.increaseIndent() } else { - p.emitListRange((*Printer).emitStatement, body.AsNode(), body.Statements, LFMultiLineFunctionBodyStatements, statementOffset, -1) + p.emitListRange((*Printer).emitStatement, body.AsNode(), body.Statements(), LFMultiLineFunctionBodyStatements, statementOffset, -1) } - p.emitDetachedCommentsAfterStatementList(body.AsNode(), body.Statements.Loc, detachedState) + p.emitDetachedCommentsAfterStatementList(body.AsNode(), body.Statements().Loc, detachedState) p.decreaseIndent() // !!! Emit comment after Strada migration ////p.emitTokenEx(ast.KindCloseBraceToken, body.Statements.End(), WriteKindPunctuation, body.AsNode(), tefNone) - p.emitTokenEx(ast.KindCloseBraceToken, body.Statements.End(), WriteKindPunctuation, body.AsNode(), tefNoComments) + p.emitTokenEx(ast.KindCloseBraceToken, body.Statements().End(), WriteKindPunctuation, body.AsNode(), tefNoComments) if p.OnAfterEmitNode != nil { p.OnAfterEmitNode(body.AsNode()) @@ -1658,8 +1658,8 @@ func (p *Printer) emitPropertySignature(node *ast.PropertySignatureDeclaration) state := p.enterNode(node.AsNode()) p.emitModifierList(node.AsNode(), node.Modifiers(), false /*allowDecorators*/) p.emitPropertyName(node.Name()) - p.emitTokenNode(node.PostfixToken) - p.emitTypeAnnotation(node.Type) + p.emitTokenNode(node.PostfixToken()) + p.emitTypeAnnotation(node.Type()) p.writeTrailingSemicolon() p.exitNode(node.AsNode(), state) } @@ -1668,9 +1668,9 @@ func (p *Printer) emitPropertyDeclaration(node *ast.PropertyDeclaration) { state := p.enterNode(node.AsNode()) p.emitModifierList(node.AsNode(), node.Modifiers(), true /*allowDecorators*/) p.emitPropertyName(node.Name()) - p.emitTokenNode(node.PostfixToken) - p.emitTypeAnnotation(node.Type) - p.emitInitializer(node.Initializer, greatestEnd(node.Name().End(), node.Type, node.PostfixToken), node.AsNode()) + p.emitTokenNode(node.PostfixToken()) + p.emitTypeAnnotation(node.Type()) + p.emitInitializer(node.Initializer(), greatestEnd(node.Name().End(), node.Type(), node.PostfixToken()), node.AsNode()) p.writeTrailingSemicolon() p.exitNode(node.AsNode(), state) } @@ -1679,7 +1679,7 @@ func (p *Printer) emitMethodSignature(node *ast.MethodSignatureDeclaration) { state := p.enterNode(node.AsNode()) p.emitModifierList(node.AsNode(), node.Modifiers(), false /*allowDecorators*/) p.emitPropertyName(node.Name()) - p.emitTokenNode(node.PostfixToken) + p.emitTokenNode(node.PostfixToken()) indented := p.shouldEmitIndented(node.AsNode()) p.increaseIndentIf(indented) p.pushNameGenerationScope(node.AsNode()) @@ -1693,14 +1693,14 @@ func (p *Printer) emitMethodSignature(node *ast.MethodSignatureDeclaration) { func (p *Printer) emitMethodDeclaration(node *ast.MethodDeclaration) { state := p.enterNode(node.AsNode()) p.emitModifierList(node.AsNode(), node.Modifiers(), true /*allowDecorators*/) - p.emitTokenNode(node.AsteriskToken) + p.emitTokenNode(node.AsteriskToken()) p.emitPropertyName(node.Name()) - p.emitTokenNode(node.PostfixToken) + p.emitTokenNode(node.PostfixToken()) indented := p.shouldEmitIndented(node.AsNode()) p.increaseIndentIf(indented) p.pushNameGenerationScope(node.AsNode()) p.emitSignature(node.AsNode()) - p.emitFunctionBodyNode(node.Body) + p.emitFunctionBodyNode(node.Body()) p.popNameGenerationScope(node.AsNode()) p.decreaseIndentIf(indented) p.exitNode(node.AsNode(), state) @@ -1710,7 +1710,7 @@ func (p *Printer) emitClassStaticBlockDeclaration(node *ast.ClassStaticBlockDecl state := p.enterNode(node.AsNode()) p.writeKeyword("static") p.pushNameGenerationScope(node.AsNode()) - p.emitFunctionBodyNode(node.Body) + p.emitFunctionBodyNode(node.Body()) p.popNameGenerationScope(node.AsNode()) p.exitNode(node.AsNode(), state) } @@ -1723,7 +1723,7 @@ func (p *Printer) emitConstructor(node *ast.ConstructorDeclaration) { p.increaseIndentIf(indented) p.pushNameGenerationScope(node.AsNode()) p.emitSignature(node.AsNode()) - p.emitFunctionBodyNode(node.Body) + p.emitFunctionBodyNode(node.Body()) p.popNameGenerationScope(node.AsNode()) p.decreaseIndentIf(indented) p.exitNode(node.AsNode(), state) @@ -1739,7 +1739,7 @@ func (p *Printer) emitAccessorDeclaration(token ast.Kind, node *ast.AccessorDecl p.increaseIndentIf(indented) p.pushNameGenerationScope(node.AsNode()) p.emitSignature(node.AsNode()) - p.emitFunctionBodyNode(node.Body) + p.emitFunctionBodyNode(node.Body()) p.popNameGenerationScope(node.AsNode()) p.decreaseIndentIf(indented) p.exitNode(node.AsNode(), state) @@ -1785,8 +1785,8 @@ func (p *Printer) emitIndexSignature(node *ast.IndexSignatureDeclaration) { indented := p.shouldEmitIndented(node.AsNode()) p.increaseIndentIf(indented) p.pushNameGenerationScope(node.AsNode()) - p.emitParametersForIndexSignature(node.AsNode(), node.Parameters) - p.emitTypeAnnotation(node.Type) + p.emitParametersForIndexSignature(node.AsNode(), node.Parameters()) + p.emitTypeAnnotation(node.Type()) p.writeTrailingSemicolon() p.popNameGenerationScope(node.AsNode()) p.decreaseIndentIf(indented) @@ -1883,16 +1883,16 @@ func (p *Printer) emitTypePredicateParameterName(node *ast.TypePredicateParamete func (p *Printer) emitTypePredicate(node *ast.TypePredicateNode) { state := p.enterNode(node.AsNode()) - if node.AssertsModifier != nil { - p.emitTokenNode(node.AssertsModifier) + if node.AssertsModifier() != nil { + p.emitTokenNode(node.AssertsModifier()) p.writeSpace() } - p.emitTypePredicateParameterName(node.ParameterName) - if node.Type != nil { + p.emitTypePredicateParameterName(node.ParameterName()) + if node.Type() != nil { p.writeSpace() p.writeKeyword("is") p.writeSpace() - p.emitTypeNodeOutsideExtends(node.Type) + p.emitTypeNodeOutsideExtends(node.Type()) } p.exitNode(node.AsNode(), state) } @@ -1910,8 +1910,8 @@ func (p *Printer) emitTypeArguments(parentNode *ast.Node, nodes *ast.TypeArgumen func (p *Printer) emitTypeReference(node *ast.TypeReferenceNode) { state := p.enterNode(node.AsNode()) - p.emitEntityName(node.TypeName) - p.emitTypeArguments(node.AsNode(), node.TypeArguments) + p.emitEntityName(node.TypeName()) + p.emitTypeArguments(node.AsNode(), node.TypeArguments()) p.exitNode(node.AsNode(), state) } @@ -1922,7 +1922,7 @@ func (p *Printer) emitReturnType(node *ast.TypeNode) { } p.writePunctuation("=>") p.writeSpace() - if p.inExtends && node.Kind == ast.KindInferType && node.AsInferTypeNode().TypeParameter.AsTypeParameterDeclaration().Constraint != nil { + if p.inExtends && node.Kind == ast.KindInferType && node.AsInferTypeNode().TypeParameter().AsTypeParameterDeclaration().Constraint() != nil { // if the parent FunctionTypeNode or ConstructorTypeNode is in the `extends` clause of a ConditionalTypeNode, // we must parenthesize `infer ... extends ...` so as not to result in an ambiguous parse. // @@ -1940,10 +1940,10 @@ func (p *Printer) emitFunctionType(node *ast.FunctionTypeNode) { p.increaseIndentIf(indented) p.pushNameGenerationScope(node.AsNode()) // !!! in the old emitter, quickinfo uses type arguments in place of type parameters for instantiated signatures - p.emitTypeParameters(node.AsNode(), node.TypeParameters) - p.emitParameters(node.AsNode(), node.Parameters) + p.emitTypeParameters(node.AsNode(), node.TypeParameters()) + p.emitParameters(node.AsNode(), node.Parameters()) p.writeSpace() - p.emitReturnType(node.Type) + p.emitReturnType(node.Type()) p.popNameGenerationScope(node.AsNode()) p.decreaseIndentIf(indented) p.exitNode(node.AsNode(), state) @@ -1958,10 +1958,10 @@ func (p *Printer) emitConstructorType(node *ast.ConstructorTypeNode) { p.increaseIndentIf(indented) p.pushNameGenerationScope(node.AsNode()) // !!! in the old emitter, quickinfo uses type arguments in place of type parameters for instantiated signatures - p.emitTypeParameters(node.AsNode(), node.TypeParameters) - p.emitParameters(node.AsNode(), node.Parameters) + p.emitTypeParameters(node.AsNode(), node.TypeParameters()) + p.emitParameters(node.AsNode(), node.Parameters()) p.writeSpace() - p.emitReturnType(node.Type) + p.emitReturnType(node.Type()) p.popNameGenerationScope(node.AsNode()) p.decreaseIndentIf(indented) p.exitNode(node.AsNode(), state) @@ -1971,18 +1971,18 @@ func (p *Printer) emitTypeQuery(node *ast.TypeQueryNode) { state := p.enterNode(node.AsNode()) p.writeKeyword("typeof") p.writeSpace() - p.emitEntityName(node.ExprName) - p.emitTypeArguments(node.AsNode(), node.TypeArguments) + p.emitEntityName(node.ExprName()) + p.emitTypeArguments(node.AsNode(), node.TypeArguments()) p.exitNode(node.AsNode(), state) } func (p *Printer) emitTypeLiteral(node *ast.TypeLiteralNode) { state := p.enterNode(node.AsNode()) p.pushNameGenerationScope(node.AsNode()) - p.generateAllMemberNames(node.Members) + p.generateAllMemberNames(node.Members()) p.writePunctuation("{") flags := core.IfElse(p.shouldEmitOnSingleLine(node.AsNode()), LFSingleLineTypeLiteralMembers, LFMultiLineTypeLiteralMembers) - p.emitList((*Printer).emitTypeElement, node.AsNode(), node.Members, flags|LFNoSpaceIfEmpty) + p.emitList((*Printer).emitTypeElement, node.AsNode(), node.Members(), flags|LFNoSpaceIfEmpty) p.writePunctuation("}") p.popNameGenerationScope(node.AsNode()) p.exitNode(node.AsNode(), state) @@ -1990,7 +1990,7 @@ func (p *Printer) emitTypeLiteral(node *ast.TypeLiteralNode) { func (p *Printer) emitArrayType(node *ast.ArrayTypeNode) { state := p.enterNode(node.AsNode()) - p.emitPostfixTypeOperand(node.ElementType, node.AsNode()) + p.emitPostfixTypeOperand(node.ElementType(), node.AsNode()) p.writePunctuation("[") p.writePunctuation("]") p.exitNode(node.AsNode(), state) @@ -2019,34 +2019,34 @@ func (p *Printer) emitTupleType(node *ast.TupleTypeNode) { state := p.enterNode(node.AsNode()) p.emitToken(ast.KindOpenBracketToken, node.Pos(), WriteKindPunctuation, node.AsNode()) flags := core.IfElse(p.shouldEmitOnSingleLine(node.AsNode()), LFSingleLineTupleTypeElements, LFMultiLineTupleTypeElements) - p.emitList((*Printer).emitTupleElementType, node.AsNode(), node.Elements, flags|LFNoSpaceIfEmpty) - p.emitToken(ast.KindCloseBracketToken, node.Elements.End(), WriteKindPunctuation, node.AsNode()) + p.emitList((*Printer).emitTupleElementType, node.AsNode(), node.Elements(), flags|LFNoSpaceIfEmpty) + p.emitToken(ast.KindCloseBracketToken, node.Elements().End(), WriteKindPunctuation, node.AsNode()) p.exitNode(node.AsNode(), state) } func (p *Printer) emitRestType(node *ast.RestTypeNode) { state := p.enterNode(node.AsNode()) p.writePunctuation("...") - p.emitTypeNodeOutsideExtends(node.Type) + p.emitTypeNodeOutsideExtends(node.Type()) p.exitNode(node.AsNode(), state) } func (p *Printer) emitOptionalType(node *ast.OptionalTypeNode) { state := p.enterNode(node.AsNode()) // !!! May need extra parenthesization if we also have JSDocNullableType - p.emitPostfixTypeOperand(node.Type, node.AsNode()) + p.emitPostfixTypeOperand(node.Type(), node.AsNode()) p.writePunctuation("?") p.exitNode(node.AsNode(), state) } func (p *Printer) emitNamedTupleMember(node *ast.NamedTupleMember) { state := p.enterNode(node.AsNode()) - p.emitPunctuationNode(node.DotDotDotToken) + p.emitPunctuationNode(node.DotDotDotToken()) p.emitIdentifierName(node.Name().AsIdentifier()) - p.emitPunctuationNode(node.QuestionToken) - p.emitToken(ast.KindColonToken, greatestEnd(node.Name().End(), node.QuestionToken), WriteKindPunctuation, node.AsNode()) + p.emitPunctuationNode(node.QuestionToken()) + p.emitToken(ast.KindColonToken, greatestEnd(node.Name().End(), node.QuestionToken()), WriteKindPunctuation, node.AsNode()) p.writeSpace() - p.emitTypeNodeOutsideExtends(node.Type) + p.emitTypeNodeOutsideExtends(node.Type()) p.exitNode(node.AsNode(), state) } @@ -2056,7 +2056,7 @@ func (p *Printer) emitUnionTypeConstituent(node *ast.TypeNode) { func (p *Printer) emitUnionType(node *ast.UnionTypeNode) { state := p.enterNode(node.AsNode()) - p.emitList((*Printer).emitUnionTypeConstituent, node.AsNode(), node.Types, LFUnionTypeConstituents) + p.emitList((*Printer).emitUnionTypeConstituent, node.AsNode(), node.Types(), LFUnionTypeConstituents) p.exitNode(node.AsNode(), state) } @@ -2066,36 +2066,36 @@ func (p *Printer) emitIntersectionTypeConstituent(node *ast.TypeNode) { func (p *Printer) emitIntersectionType(node *ast.IntersectionTypeNode) { state := p.enterNode(node.AsNode()) - p.emitList((*Printer).emitIntersectionTypeConstituent, node.AsNode(), node.Types, LFIntersectionTypeConstituents /*, parenthesizer.parenthesizeConstituentTypeOfIntersectionType*/) // !!! + p.emitList((*Printer).emitIntersectionTypeConstituent, node.AsNode(), node.Types(), LFIntersectionTypeConstituents /*, parenthesizer.parenthesizeConstituentTypeOfIntersectionType*/) // !!! p.exitNode(node.AsNode(), state) } func (p *Printer) emitConditionalType(node *ast.ConditionalTypeNode) { state := p.enterNode(node.AsNode()) - p.emitTypeNode(node.CheckType, ast.TypePrecedenceUnion) + p.emitTypeNode(node.CheckType(), ast.TypePrecedenceUnion) p.writeSpace() p.writeKeyword("extends") p.writeSpace() - p.emitTypeNodeInExtends(node.ExtendsType) + p.emitTypeNodeInExtends(node.ExtendsType()) p.writeSpace() p.writePunctuation("?") p.writeSpace() - p.emitTypeNodeOutsideExtends(node.TrueType) + p.emitTypeNodeOutsideExtends(node.TrueType()) p.writeSpace() p.writePunctuation(":") p.writeSpace() - p.emitTypeNodeOutsideExtends(node.FalseType) + p.emitTypeNodeOutsideExtends(node.FalseType()) p.exitNode(node.AsNode(), state) } func (p *Printer) emitInferTypeParameter(node *ast.TypeParameterDeclaration) { state := p.enterNode(node.AsNode()) p.emitBindingIdentifier(node.Name().AsIdentifier()) - if node.Constraint != nil { + if node.Constraint() != nil { p.writeSpace() p.writeKeyword("extends") p.writeSpace() - p.emitTypeNodeInExtends(node.Constraint) + p.emitTypeNodeInExtends(node.Constraint()) } p.exitNode(node.AsNode(), state) } @@ -2104,14 +2104,14 @@ func (p *Printer) emitInferType(node *ast.InferTypeNode) { state := p.enterNode(node.AsNode()) p.writeKeyword("infer") p.writeSpace() - p.emitInferTypeParameter(node.TypeParameter.AsTypeParameterDeclaration()) + p.emitInferTypeParameter(node.TypeParameter().AsTypeParameterDeclaration()) p.exitNode(node.AsNode(), state) } func (p *Printer) emitParenthesizedType(node *ast.ParenthesizedTypeNode) { state := p.enterNode(node.AsNode()) p.writePunctuation("(") - p.emitTypeNodeOutsideExtends(node.Type) + p.emitTypeNodeOutsideExtends(node.Type()) p.writePunctuation(")") p.exitNode(node.AsNode(), state) } @@ -2126,15 +2126,15 @@ func (p *Printer) emitTypeOperator(node *ast.TypeOperatorNode) { state := p.enterNode(node.AsNode()) p.emitToken(node.Operator, node.Pos(), WriteKindKeyword, node.AsNode()) p.writeSpace() - p.emitTypeNode(node.Type, core.IfElse(node.Operator == ast.KindReadonlyKeyword, ast.TypePrecedencePostfix, ast.TypePrecedenceTypeOperator)) + p.emitTypeNode(node.Type(), core.IfElse(node.Operator == ast.KindReadonlyKeyword, ast.TypePrecedencePostfix, ast.TypePrecedenceTypeOperator)) p.exitNode(node.AsNode(), state) } func (p *Printer) emitIndexedAccessType(node *ast.IndexedAccessTypeNode) { state := p.enterNode(node.AsNode()) - p.emitPostfixTypeOperand(node.ObjectType, node.AsNode()) + p.emitPostfixTypeOperand(node.ObjectType(), node.AsNode()) p.writePunctuation("[") - p.emitTypeNodeOutsideExtends(node.IndexType) + p.emitTypeNodeOutsideExtends(node.IndexType()) p.writePunctuation("]") p.exitNode(node.AsNode(), state) } @@ -2145,7 +2145,7 @@ func (p *Printer) emitMappedTypeParameter(node *ast.TypeParameterDeclaration) { p.writeSpace() p.writeKeyword("in") p.writeSpace() - p.emitTypeNodeOutsideExtends(node.Constraint) + p.emitTypeNodeOutsideExtends(node.Constraint()) p.exitNode(node.AsNode(), state) } @@ -2159,42 +2159,42 @@ func (p *Printer) emitMappedType(node *ast.MappedTypeNode) { p.writeLine() p.increaseIndent() } - if node.ReadonlyToken != nil { - p.emitTokenNode(node.ReadonlyToken) - if node.ReadonlyToken.Kind != ast.KindReadonlyKeyword { + if node.ReadonlyToken() != nil { + p.emitTokenNode(node.ReadonlyToken()) + if node.ReadonlyToken().Kind != ast.KindReadonlyKeyword { p.writeKeyword("readonly") } p.writeSpace() } p.writePunctuation("[") - p.emitMappedTypeParameter(node.TypeParameter.AsTypeParameterDeclaration()) - if node.NameType != nil { + p.emitMappedTypeParameter(node.TypeParameter().AsTypeParameterDeclaration()) + if node.NameType() != nil { p.writeSpace() p.writeKeyword("as") p.writeSpace() - p.emitTypeNodeOutsideExtends(node.NameType) + p.emitTypeNodeOutsideExtends(node.NameType()) } p.writePunctuation("]") - if node.QuestionToken != nil { - p.emitPunctuationNode(node.QuestionToken) - if node.QuestionToken.Kind != ast.KindQuestionToken { + if node.QuestionToken() != nil { + p.emitPunctuationNode(node.QuestionToken()) + if node.QuestionToken().Kind != ast.KindQuestionToken { p.writePunctuation("?") } } - if node.Type != nil { + if node.Type() != nil { p.writePunctuation(":") p.writeSpace() - p.emitTypeNodeOutsideExtends(node.Type) + p.emitTypeNodeOutsideExtends(node.Type()) } p.writeTrailingSemicolon() - if node.Members != nil { - if len(node.Members.Nodes) > 0 { + if node.Members() != nil { + if len(node.Members().Nodes) > 0 { if singleLine { p.writeSpace() } else { p.writeLine() } - p.emitList((*Printer).emitTypeElement, node.AsNode(), node.Members, LFPreserveLines) + p.emitList((*Printer).emitTypeElement, node.AsNode(), node.Members(), LFPreserveLines) } } if singleLine { @@ -2209,14 +2209,14 @@ func (p *Printer) emitMappedType(node *ast.MappedTypeNode) { func (p *Printer) emitLiteralType(node *ast.LiteralTypeNode) { state := p.enterNode(node.AsNode()) - p.emitExpression(node.Literal, ast.OperatorPrecedenceComma) + p.emitExpression(node.Literal(), ast.OperatorPrecedenceComma) p.exitNode(node.AsNode(), state) } func (p *Printer) emitTemplateTypeSpan(node *ast.TemplateLiteralTypeSpan) { state := p.enterNode(node.AsNode()) - p.emitTypeNodeOutsideExtends(node.Type) - p.emitTemplateMiddleTail(node.Literal) + p.emitTypeNodeOutsideExtends(node.Type()) + p.emitTemplateMiddleTail(node.Literal()) p.exitNode(node.AsNode(), state) } @@ -2226,8 +2226,8 @@ func (p *Printer) emitTemplateTypeSpanNode(node *ast.TemplateLiteralTypeSpanNode func (p *Printer) emitTemplateType(node *ast.TemplateLiteralTypeNode) { state := p.enterNode(node.AsNode()) - p.emitTemplateHead(node.Head.AsTemplateHead()) - p.emitList((*Printer).emitTemplateTypeSpanNode, node.AsNode(), node.TemplateSpans, LFTemplateExpressionSpans) + p.emitTemplateHead(node.Head().AsTemplateHead()) + p.emitList((*Printer).emitTemplateTypeSpanNode, node.AsNode(), node.TemplateSpans(), LFTemplateExpressionSpans) p.exitNode(node.AsNode(), state) } @@ -2238,7 +2238,7 @@ func (p *Printer) emitImportTypeNodeAttributes(node *ast.ImportAttributes) { p.writeKeyword(core.IfElse(node.Token == ast.KindAssertKeyword, "assert", "with")) p.writePunctuation(":") p.writeSpace() - p.emitList((*Printer).emitImportAttributeNode, node.AsNode(), node.Attributes, LFImportAttributes) + p.emitList((*Printer).emitImportAttributeNode, node.AsNode(), node.Attributes(), LFImportAttributes) p.writeSpace() p.writePunctuation("}") p.exitNode(node.AsNode(), state) @@ -2252,18 +2252,18 @@ func (p *Printer) emitImportTypeNode(node *ast.ImportTypeNode) { } p.writeKeyword("import") p.writePunctuation("(") - p.emitTypeNodeOutsideExtends(node.Argument) - if node.Attributes != nil { + p.emitTypeNodeOutsideExtends(node.Argument()) + if node.Attributes() != nil { p.writePunctuation(",") p.writeSpace() - p.emitImportTypeNodeAttributes(node.Attributes.AsImportAttributes()) + p.emitImportTypeNodeAttributes(node.Attributes().AsImportAttributes()) } p.writePunctuation(")") - if node.Qualifier != nil { + if node.Qualifier() != nil { p.writePunctuation(".") - p.emitEntityName(node.Qualifier) + p.emitEntityName(node.Qualifier()) } - p.emitTypeArguments(node.AsNode(), node.TypeArguments) + p.emitTypeArguments(node.AsNode(), node.TypeArguments()) p.exitNode(node.AsNode(), state) } @@ -2403,7 +2403,7 @@ func (p *Printer) emitTypeNode(node *ast.TypeNode, precedence ast.TypePrecedence func (p *Printer) emitObjectBindingPattern(node *ast.BindingPattern) { state := p.enterNode(node.AsNode()) p.writePunctuation("{") - p.emitList((*Printer).emitBindingElementNode, node.AsNode(), node.Elements, LFObjectBindingPatternElements) + p.emitList((*Printer).emitBindingElementNode, node.AsNode(), node.Elements(), LFObjectBindingPatternElements) p.writePunctuation("}") p.exitNode(node.AsNode(), state) } @@ -2411,23 +2411,23 @@ func (p *Printer) emitObjectBindingPattern(node *ast.BindingPattern) { func (p *Printer) emitArrayBindingPattern(node *ast.BindingPattern) { state := p.enterNode(node.AsNode()) p.writePunctuation("[") - p.emitList((*Printer).emitBindingElementNode, node.AsNode(), node.Elements, LFArrayBindingPatternElements) + p.emitList((*Printer).emitBindingElementNode, node.AsNode(), node.Elements(), LFArrayBindingPatternElements) p.writePunctuation("]") p.exitNode(node.AsNode(), state) } func (p *Printer) emitBindingElement(node *ast.BindingElement) { state := p.enterNode(node.AsNode()) - p.emitTokenNode(node.DotDotDotToken) - if node.PropertyName != nil { - p.emitPropertyName(node.PropertyName) + p.emitTokenNode(node.DotDotDotToken()) + if node.PropertyName() != nil { + p.emitPropertyName(node.PropertyName()) p.writePunctuation(":") p.writeSpace() } // Old parser used `OmittedExpression` as a substitute for `Elision`. New parser uses a `BindingElement` with nil members if name := node.Name(); name != nil { p.emitBindingName(name) - p.emitInitializer(node.Initializer, node.Name().End(), node.AsNode()) + p.emitInitializer(node.Initializer(), node.Name().End(), node.AsNode()) } p.exitNode(node.AsNode(), state) } @@ -2443,20 +2443,20 @@ func (p *Printer) emitJSDocAllType(node *ast.Node) { func (p *Printer) emitJSDocNonNullableType(node *ast.JSDocNonNullableType) { state := p.enterNode(node.AsNode()) p.writePunctuation("!") - p.emitTypeNode(node.Type, ast.TypePrecedenceNonArray) + p.emitTypeNode(node.Type(), ast.TypePrecedenceNonArray) p.exitNode(node.AsNode(), state) } func (p *Printer) emitJSDocNullableType(node *ast.JSDocNullableType) { state := p.enterNode(node.AsNode()) p.writePunctuation("?") - p.emitTypeNode(node.Type, ast.TypePrecedenceNonArray) + p.emitTypeNode(node.Type(), ast.TypePrecedenceNonArray) p.exitNode(node.AsNode(), state) } func (p *Printer) emitJSDocOptionalType(node *ast.JSDocOptionalType) { state := p.enterNode(node.AsNode()) - p.emitTypeNode(node.Type, ast.TypePrecedenceJSDoc) + p.emitTypeNode(node.Type(), ast.TypePrecedenceJSDoc) p.writePunctuation("=") p.exitNode(node.AsNode(), state) } @@ -2464,7 +2464,7 @@ func (p *Printer) emitJSDocOptionalType(node *ast.JSDocOptionalType) { func (p *Printer) emitJSDocVariadicType(node *ast.JSDocVariadicType) { state := p.enterNode(node.AsNode()) p.writePunctuation("...") - p.emitTypeNode(node.Type, ast.TypePrecedenceJSDoc) + p.emitTypeNode(node.Type(), ast.TypePrecedenceJSDoc) p.exitNode(node.AsNode(), state) } @@ -2482,7 +2482,7 @@ func (p *Printer) emitArrayLiteralExpressionElement(node *ast.Expression) { func (p *Printer) emitArrayLiteralExpression(node *ast.ArrayLiteralExpression) { state := p.enterNode(node.AsNode()) - p.emitList((*Printer).emitArrayLiteralExpressionElement, node.AsNode(), node.Elements, LFArrayLiteralExpressionElements|core.IfElse(node.MultiLine, LFPreferNewLine, LFNone)) + p.emitList((*Printer).emitArrayLiteralExpressionElement, node.AsNode(), node.Elements(), LFArrayLiteralExpressionElements|core.IfElse(node.MultiLine, LFPreferNewLine, LFNone)) p.exitNode(node.AsNode(), state) } @@ -2491,10 +2491,10 @@ func (p *Printer) emitObjectLiteralExpression(node *ast.ObjectLiteralExpression) indented := p.shouldEmitIndented(node.AsNode()) p.increaseIndentIf(indented) p.pushNameGenerationScope(node.AsNode()) - p.generateAllMemberNames(node.Properties) - p.emitList((*Printer).emitObjectLiteralElement, node.AsNode(), node.Properties, LFObjectLiteralExpressionProperties| + p.generateAllMemberNames(node.Properties()) + p.emitList((*Printer).emitObjectLiteralElement, node.AsNode(), node.Properties(), LFObjectLiteralExpressionProperties| core.IfElse(node.MultiLine, LFPreferNewLine, LFNone)| - core.IfElse(p.shouldAllowTrailingComma(node.AsNode(), node.Properties), LFAllowTrailingComma, LFNone)) + core.IfElse(p.shouldAllowTrailingComma(node.AsNode(), node.Properties()), LFAllowTrailingComma, LFNone)) p.popNameGenerationScope(node.AsNode()) p.decreaseIndentIf(indented) p.exitNode(node.AsNode(), state) @@ -2519,27 +2519,27 @@ func (p *Printer) mayNeedDotDotForPropertyAccess(expression *ast.Expression) boo func (p *Printer) emitPropertyAccessExpression(node *ast.PropertyAccessExpression) { state := p.enterNode(node.AsNode()) - p.emitExpression(node.Expression, core.IfElse(ast.IsOptionalChain(node.AsNode()), ast.OperatorPrecedenceOptionalChain, ast.OperatorPrecedenceMember)) - token := node.QuestionDotToken + p.emitExpression(node.Expression(), core.IfElse(ast.IsOptionalChain(node.AsNode()), ast.OperatorPrecedenceOptionalChain, ast.OperatorPrecedenceMember)) + token := node.QuestionDotToken() if token == nil { token = p.emitContext.Factory.NewToken(ast.KindDotToken) - token.Loc = core.NewTextRange(node.Expression.End(), node.Name().Pos()) + token.Loc = core.NewTextRange(node.Expression().End(), node.Name().Pos()) p.emitContext.AddEmitFlags(token, EFNoSourceMap) } - linesBeforeDot := p.getLinesBetweenNodes(node.AsNode(), node.Expression, token) + linesBeforeDot := p.getLinesBetweenNodes(node.AsNode(), node.Expression(), token) p.writeLineRepeat(linesBeforeDot) p.increaseIndentIf(linesBeforeDot > 0) shouldEmitDotDot := token.Kind != ast.KindQuestionDotToken && - p.mayNeedDotDotForPropertyAccess(node.Expression) && + p.mayNeedDotDotForPropertyAccess(node.Expression()) && !p.writer.HasTrailingComment() && !p.writer.HasTrailingWhitespace() if shouldEmitDotDot { p.writePunctuation(".") } - if node.QuestionDotToken != nil { + if node.QuestionDotToken() != nil { p.emitTokenNode(token) } else { - p.emitToken(ast.KindDotToken, node.Expression.End(), WriteKindPunctuation, node.AsNode()) + p.emitToken(ast.KindDotToken, node.Expression().End(), WriteKindPunctuation, node.AsNode()) } linesAfterDot := p.getLinesBetweenNodes(node.AsNode(), token, node.Name()) p.writeLineRepeat(linesAfterDot) @@ -2552,11 +2552,11 @@ func (p *Printer) emitPropertyAccessExpression(node *ast.PropertyAccessExpressio func (p *Printer) emitElementAccessExpression(node *ast.ElementAccessExpression) { state := p.enterNode(node.AsNode()) - p.emitExpression(node.Expression, core.IfElse(ast.IsOptionalChain(node.AsNode()), ast.OperatorPrecedenceOptionalChain, ast.OperatorPrecedenceMember)) - p.emitTokenNode(node.QuestionDotToken) - p.emitToken(ast.KindOpenBracketToken, greatestEnd(-1, node.Expression, node.QuestionDotToken), WriteKindPunctuation, node.AsNode()) - p.emitExpression(node.ArgumentExpression, ast.OperatorPrecedenceComma) - p.emitToken(ast.KindCloseBracketToken, node.ArgumentExpression.End(), WriteKindPunctuation, node.AsNode()) + p.emitExpression(node.Expression(), core.IfElse(ast.IsOptionalChain(node.AsNode()), ast.OperatorPrecedenceOptionalChain, ast.OperatorPrecedenceMember)) + p.emitTokenNode(node.QuestionDotToken()) + p.emitToken(ast.KindOpenBracketToken, greatestEnd(-1, node.Expression(), node.QuestionDotToken()), WriteKindPunctuation, node.AsNode()) + p.emitExpression(node.ArgumentExpression(), ast.OperatorPrecedenceComma) + p.emitToken(ast.KindCloseBracketToken, node.ArgumentExpression().End(), WriteKindPunctuation, node.AsNode()) p.exitNode(node.AsNode(), state) } @@ -2582,10 +2582,10 @@ func (p *Printer) emitCallee(callee *ast.Expression, parentNode *ast.Node) { func (p *Printer) emitCallExpression(node *ast.CallExpression) { state := p.enterNode(node.AsNode()) - p.emitCallee(node.Expression, node.AsNode()) - p.emitTokenNode(node.QuestionDotToken) - p.emitTypeArguments(node.AsNode(), node.TypeArguments) - p.emitList((*Printer).emitArgument, node.AsNode(), node.Arguments, LFCallExpressionArguments) + p.emitCallee(node.Expression(), node.AsNode()) + p.emitTokenNode(node.QuestionDotToken()) + p.emitTypeArguments(node.AsNode(), node.TypeArguments()) + p.emitList((*Printer).emitArgument, node.AsNode(), node.Arguments(), LFCallExpressionArguments) p.exitNode(node.AsNode(), state) } @@ -2593,14 +2593,14 @@ func (p *Printer) emitNewExpression(node *ast.NewExpression) { state := p.enterNode(node.AsNode()) p.emitToken(ast.KindNewKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) p.writeSpace() - if ast.SkipPartiallyEmittedExpressions(node.Expression).Kind == ast.KindCallExpression { + if ast.SkipPartiallyEmittedExpressions(node.Expression()).Kind == ast.KindCallExpression { // Parenthesize `C()` inside of a NewExpression so it is treated as `new (C())` and not `new C()` - p.emitExpression(node.Expression, ast.OperatorPrecedenceParentheses) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceParentheses) } else { - p.emitExpression(node.Expression, ast.OperatorPrecedenceMember) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceMember) } - p.emitTypeArguments(node.AsNode(), node.TypeArguments) - p.emitList((*Printer).emitArgument, node.AsNode(), node.Arguments, LFNewExpressionArguments) + p.emitTypeArguments(node.AsNode(), node.TypeArguments()) + p.emitList((*Printer).emitArgument, node.AsNode(), node.Arguments(), LFNewExpressionArguments) p.exitNode(node.AsNode(), state) } @@ -2617,32 +2617,32 @@ func (p *Printer) emitTemplateLiteral(node *ast.TemplateLiteral) { func (p *Printer) emitTaggedTemplateExpression(node *ast.TaggedTemplateExpression) { state := p.enterNode(node.AsNode()) - p.emitCallee(node.Tag, node.AsNode()) - p.emitTypeArguments(node.AsNode(), node.TypeArguments) + p.emitCallee(node.Tag(), node.AsNode()) + p.emitTypeArguments(node.AsNode(), node.TypeArguments()) p.writeSpace() - p.emitTemplateLiteral(node.Template) + p.emitTemplateLiteral(node.Template()) p.exitNode(node.AsNode(), state) } func (p *Printer) emitTypeAssertionExpression(node *ast.TypeAssertion) { state := p.enterNode(node.AsNode()) p.writePunctuation("<") - p.emitTypeNodeOutsideExtends(node.Type) + p.emitTypeNodeOutsideExtends(node.Type()) p.writePunctuation(">") - p.emitExpression(node.Expression, ast.OperatorPrecedenceUpdate) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceUpdate) p.exitNode(node.AsNode(), state) } func (p *Printer) emitParenthesizedExpression(node *ast.ParenthesizedExpression) { state := p.enterNode(node.AsNode()) openParenPos := p.emitToken(ast.KindOpenParenToken, node.Pos(), WriteKindPunctuation, node.AsNode()) - indented := p.writeLineSeparatorsAndIndentBefore(node.Expression, node.AsNode()) - p.emitExpression(node.Expression, ast.OperatorPrecedenceComma) - p.writeLineSeparatorsAfter(node.Expression, node.AsNode()) + indented := p.writeLineSeparatorsAndIndentBefore(node.Expression(), node.AsNode()) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceComma) + p.writeLineSeparatorsAfter(node.Expression(), node.AsNode()) p.decreaseIndentIf(indented) closeParenPos := openParenPos - if node.Expression != nil { - closeParenPos = node.Expression.End() + if node.Expression() != nil { + closeParenPos = node.Expression().End() } p.emitToken(ast.KindCloseParenToken, closeParenPos, WriteKindPunctuation, node.AsNode()) p.exitNode(node.AsNode(), state) @@ -2653,14 +2653,14 @@ func (p *Printer) emitFunctionExpression(node *ast.FunctionExpression) { p.generateNameIfNeeded(node.Name()) p.emitModifierList(node.AsNode(), node.Modifiers(), false /*allowDecorators*/) p.writeKeyword("function") - p.emitTokenNode(node.AsteriskToken) + p.emitTokenNode(node.AsteriskToken()) p.writeSpace() p.emitIdentifierNameNode(node.Name()) indented := p.shouldEmitIndented(node.AsNode()) p.increaseIndentIf(indented) p.pushNameGenerationScope(node.AsNode()) p.emitSignature(node.AsNode()) - p.emitFunctionBodyNode(node.Body) + p.emitFunctionBodyNode(node.Body()) p.popNameGenerationScope(node.AsNode()) p.decreaseIndentIf(indented) p.exitNode(node.AsNode(), state) @@ -2690,13 +2690,13 @@ func (p *Printer) emitArrowFunction(node *ast.ArrowFunction) { indented := p.shouldEmitIndented(node.AsNode()) p.increaseIndentIf(indented) p.pushNameGenerationScope(node.AsNode()) - p.emitTypeParameters(node.AsNode(), node.TypeParameters) - p.emitParametersForArrow(node.AsNode(), node.Parameters) - p.emitTypeAnnotation(node.Type) + p.emitTypeParameters(node.AsNode(), node.TypeParameters()) + p.emitParametersForArrow(node.AsNode(), node.Parameters()) + p.emitTypeAnnotation(node.Type()) p.writeSpace() - p.emitTokenNode(node.EqualsGreaterThanToken) + p.emitTokenNode(node.EqualsGreaterThanToken()) p.writeSpace() - p.emitConciseBody(node.Body) + p.emitConciseBody(node.Body()) p.popNameGenerationScope(node.AsNode()) p.decreaseIndentIf(indented) p.exitNode(node.AsNode(), state) @@ -2706,7 +2706,7 @@ func (p *Printer) emitDeleteExpression(node *ast.DeleteExpression) { state := p.enterNode(node.AsNode()) p.emitToken(ast.KindDeleteKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) p.writeSpace() - p.emitExpression(node.Expression, ast.OperatorPrecedenceUnary) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceUnary) p.exitNode(node.AsNode(), state) } @@ -2714,7 +2714,7 @@ func (p *Printer) emitTypeOfExpression(node *ast.TypeOfExpression) { state := p.enterNode(node.AsNode()) p.emitToken(ast.KindTypeOfKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) p.writeSpace() - p.emitExpression(node.Expression, ast.OperatorPrecedenceUnary) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceUnary) p.exitNode(node.AsNode(), state) } @@ -2722,7 +2722,7 @@ func (p *Printer) emitVoidExpression(node *ast.VoidExpression) { state := p.enterNode(node.AsNode()) p.emitToken(ast.KindVoidKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) p.writeSpace() - p.emitExpression(node.Expression, ast.OperatorPrecedenceUnary) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceUnary) p.exitNode(node.AsNode(), state) } @@ -2730,14 +2730,14 @@ func (p *Printer) emitAwaitExpression(node *ast.AwaitExpression) { state := p.enterNode(node.AsNode()) p.emitToken(ast.KindAwaitKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) p.writeSpace() - p.emitExpression(node.Expression, ast.OperatorPrecedenceUnary) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceUnary) p.exitNode(node.AsNode(), state) } func (p *Printer) emitPrefixUnaryExpression(node *ast.PrefixUnaryExpression) { state := p.enterNode(node.AsNode()) operator := node.Operator - operand := node.Operand + operand := node.Operand() p.emitToken(operator, node.Pos(), WriteKindOperator, node.AsNode()) // In some cases, we need to emit a space between the operator and the operand. One obvious case @@ -2760,14 +2760,14 @@ func (p *Printer) emitPrefixUnaryExpression(node *ast.PrefixUnaryExpression) { } } - p.emitExpression(node.Operand, ast.OperatorPrecedenceUnary) + p.emitExpression(node.Operand(), ast.OperatorPrecedenceUnary) p.exitNode(node.AsNode(), state) } func (p *Printer) emitPostfixUnaryExpression(node *ast.PostfixUnaryExpression) { state := p.enterNode(node.AsNode()) - p.emitExpression(node.Operand, ast.OperatorPrecedenceLeftHandSide) - p.emitToken(node.Operator, node.Operand.End(), WriteKindOperator, node.AsNode()) + p.emitExpression(node.Operand(), ast.OperatorPrecedenceLeftHandSide) + p.emitToken(node.Operator, node.Operand().End(), WriteKindOperator, node.AsNode()) p.exitNode(node.AsNode(), state) } @@ -2783,15 +2783,15 @@ func (p *Printer) getLiteralKindOfBinaryPlusOperand(node *ast.Expression) ast.Ki } if node.Kind == ast.KindBinaryExpression { - if n := node.AsBinaryExpression(); n.OperatorToken.Kind == ast.KindPlusToken { + if n := node.AsBinaryExpression(); n.OperatorToken().Kind == ast.KindPlusToken { // !!! Determine if caching this is worthwhile over recomputing ////if n.cachedLiteralKind != KindUnknown { //// return n.cachedLiteralKind; ////} - leftKind := p.getLiteralKindOfBinaryPlusOperand(n.Left) + leftKind := p.getLiteralKindOfBinaryPlusOperand(n.Left()) literalKind := ast.KindUnknown - if ast.IsLiteralKind(leftKind) && leftKind == p.getLiteralKindOfBinaryPlusOperand(n.Right) { + if ast.IsLiteralKind(leftKind) && leftKind == p.getLiteralKindOfBinaryPlusOperand(n.Right()) { literalKind = leftKind } @@ -2839,9 +2839,9 @@ func (p *Printer) getBinaryExpressionPrecedence(node *ast.BinaryExpression) (lef case ast.OperatorPrecedenceShift: rightPrec = ast.OperatorPrecedenceAdditive case ast.OperatorPrecedenceAdditive: - if node.OperatorToken.Kind == ast.KindPlusToken && isBinaryOperation(node.Right, ast.KindPlusToken) { - leftKind := p.getLiteralKindOfBinaryPlusOperand(node.Left) - if ast.IsLiteralKind(leftKind) && leftKind == p.getLiteralKindOfBinaryPlusOperand(node.Right) { + if node.OperatorToken().Kind == ast.KindPlusToken && isBinaryOperation(node.Right(), ast.KindPlusToken) { + leftKind := p.getLiteralKindOfBinaryPlusOperand(node.Left()) + if ast.IsLiteralKind(leftKind) && leftKind == p.getLiteralKindOfBinaryPlusOperand(node.Right()) { // No need to parenthesize the right operand when the binary operator // is plus (+) if both the left and right operands consist solely of either // literals of the same kind or binary plus (+) expressions for literals of @@ -2853,7 +2853,7 @@ func (p *Printer) getBinaryExpressionPrecedence(node *ast.BinaryExpression) (lef } rightPrec = ast.OperatorPrecedenceMultiplicative case ast.OperatorPrecedenceMultiplicative: - if node.OperatorToken.Kind == ast.KindAsteriskToken && isBinaryOperation(node.Right, ast.KindAsteriskToken) { + if node.OperatorToken().Kind == ast.KindAsteriskToken && isBinaryOperation(node.Right(), ast.KindAsteriskToken) { // No need to parenthesize the right operand when the binary operator and // operand are both * due to the associative property of mathematics: // x*(a*b) => x*a*b @@ -2871,20 +2871,20 @@ func (p *Printer) getBinaryExpressionPrecedence(node *ast.BinaryExpression) (lef func (p *Printer) emitBinaryExpression(node *ast.BinaryExpression) { leftPrec, rightPrec := p.getBinaryExpressionPrecedence(node) - if emittedLeft := ast.SkipPartiallyEmittedExpressions(node.Left); ast.NodeIsSynthesized(emittedLeft) && emittedLeft.Kind == ast.KindBinaryExpression && mixingBinaryOperatorsRequiresParentheses(node.OperatorToken.Kind, emittedLeft.AsBinaryExpression().OperatorToken.Kind) { + if emittedLeft := ast.SkipPartiallyEmittedExpressions(node.Left()); ast.NodeIsSynthesized(emittedLeft) && emittedLeft.Kind == ast.KindBinaryExpression && mixingBinaryOperatorsRequiresParentheses(node.OperatorToken().Kind, emittedLeft.AsBinaryExpression().OperatorToken().Kind) { leftPrec = ast.OperatorPrecedenceHighest } - if emittedRight := ast.SkipPartiallyEmittedExpressions(node.Right); ast.NodeIsSynthesized(emittedRight) && emittedRight.Kind == ast.KindBinaryExpression && mixingBinaryOperatorsRequiresParentheses(node.OperatorToken.Kind, emittedRight.AsBinaryExpression().OperatorToken.Kind) { + if emittedRight := ast.SkipPartiallyEmittedExpressions(node.Right()); ast.NodeIsSynthesized(emittedRight) && emittedRight.Kind == ast.KindBinaryExpression && mixingBinaryOperatorsRequiresParentheses(node.OperatorToken().Kind, emittedRight.AsBinaryExpression().OperatorToken().Kind) { rightPrec = ast.OperatorPrecedenceHighest } state := p.enterNode(node.AsNode()) - p.emitExpression(node.Left, leftPrec) - linesBeforeOperator := p.getLinesBetweenNodes(node.AsNode(), node.Left, node.OperatorToken) - linesAfterOperator := p.getLinesBetweenNodes(node.AsNode(), node.OperatorToken, node.Right) - p.writeLinesAndIndent(linesBeforeOperator, node.OperatorToken.Kind != ast.KindCommaToken /*writeSpaceIfNotIndenting*/) - p.emitTokenNodeEx(node.OperatorToken, tefNoSourceMaps) + p.emitExpression(node.Left(), leftPrec) + linesBeforeOperator := p.getLinesBetweenNodes(node.AsNode(), node.Left(), node.OperatorToken()) + linesAfterOperator := p.getLinesBetweenNodes(node.AsNode(), node.OperatorToken(), node.Right()) + p.writeLinesAndIndent(linesBeforeOperator, node.OperatorToken().Kind != ast.KindCommaToken /*writeSpaceIfNotIndenting*/) + p.emitTokenNodeEx(node.OperatorToken(), tefNoSourceMaps) p.writeLinesAndIndent(linesAfterOperator, true /*writeSpaceIfNotIndenting*/) // Binary operators should have a space before the comment starts - p.emitExpression(node.Right, rightPrec) + p.emitExpression(node.Right(), rightPrec) p.decreaseIndentIf(linesAfterOperator > 0) p.decreaseIndentIf(linesBeforeOperator > 0) p.exitNode(node.AsNode(), state) @@ -2900,21 +2900,21 @@ func (p *Printer) emitShortCircuitExpression(node *ast.Expression) { func (p *Printer) emitConditionalExpression(node *ast.ConditionalExpression) { state := p.enterNode(node.AsNode()) - linesBeforeQuestion := p.getLinesBetweenNodes(node.AsNode(), node.Condition, node.QuestionToken) - linesAfterQuestion := p.getLinesBetweenNodes(node.AsNode(), node.QuestionToken, node.WhenTrue) - linesBeforeColon := p.getLinesBetweenNodes(node.AsNode(), node.WhenTrue, node.ColonToken) - linesAfterColon := p.getLinesBetweenNodes(node.AsNode(), node.ColonToken, node.WhenFalse) - p.emitShortCircuitExpression(node.Condition) + linesBeforeQuestion := p.getLinesBetweenNodes(node.AsNode(), node.Condition(), node.QuestionToken()) + linesAfterQuestion := p.getLinesBetweenNodes(node.AsNode(), node.QuestionToken(), node.WhenTrue()) + linesBeforeColon := p.getLinesBetweenNodes(node.AsNode(), node.WhenTrue(), node.ColonToken()) + linesAfterColon := p.getLinesBetweenNodes(node.AsNode(), node.ColonToken(), node.WhenFalse()) + p.emitShortCircuitExpression(node.Condition()) p.writeLinesAndIndent(linesBeforeQuestion /*writeSpaceIfNotIndenting*/, true) - p.emitPunctuationNode(node.QuestionToken) + p.emitPunctuationNode(node.QuestionToken()) p.writeLinesAndIndent(linesAfterQuestion /*writeSpaceIfNotIndenting*/, true) - p.emitExpression(node.WhenTrue, ast.OperatorPrecedenceYield) + p.emitExpression(node.WhenTrue(), ast.OperatorPrecedenceYield) p.decreaseIndentIf(linesAfterQuestion > 0) p.decreaseIndentIf(linesBeforeQuestion > 0) p.writeLinesAndIndent(linesBeforeColon /*writeSpaceIfNotIndenting*/, true) - p.emitPunctuationNode(node.ColonToken) + p.emitPunctuationNode(node.ColonToken()) p.writeLinesAndIndent(linesAfterColon /*writeSpaceIfNotIndenting*/, true) - p.emitExpression(node.WhenFalse, ast.OperatorPrecedenceYield) + p.emitExpression(node.WhenFalse(), ast.OperatorPrecedenceYield) p.decreaseIndentIf(linesAfterColon > 0) p.decreaseIndentIf(linesBeforeColon > 0) p.exitNode(node.AsNode(), state) @@ -2922,18 +2922,18 @@ func (p *Printer) emitConditionalExpression(node *ast.ConditionalExpression) { func (p *Printer) emitTemplateExpression(node *ast.TemplateExpression) { state := p.enterNode(node.AsNode()) - p.emitTemplateHead(node.Head.AsTemplateHead()) - p.emitList((*Printer).emitTemplateSpanNode, node.AsNode(), node.TemplateSpans, LFTemplateExpressionSpans) + p.emitTemplateHead(node.Head().AsTemplateHead()) + p.emitList((*Printer).emitTemplateSpanNode, node.AsNode(), node.TemplateSpans(), LFTemplateExpressionSpans) p.exitNode(node.AsNode(), state) } func (p *Printer) emitYieldExpression(node *ast.YieldExpression) { state := p.enterNode(node.AsNode()) p.emitToken(ast.KindYieldKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) - p.emitPunctuationNode(node.AsteriskToken) - if node.Expression != nil { + p.emitPunctuationNode(node.AsteriskToken()) + if node.Expression() != nil { p.writeSpace() - p.emitExpressionNoASI(node.Expression, ast.OperatorPrecedenceDisallowComma) + p.emitExpressionNoASI(node.Expression(), ast.OperatorPrecedenceDisallowComma) } p.exitNode(node.AsNode(), state) } @@ -2941,7 +2941,7 @@ func (p *Printer) emitYieldExpression(node *ast.YieldExpression) { func (p *Printer) emitSpreadElement(node *ast.SpreadElement) { state := p.enterNode(node.AsNode()) p.emitToken(ast.KindDotDotDotToken, node.Pos(), WriteKindPunctuation, node.AsNode()) - p.emitExpression(node.Expression, ast.OperatorPrecedenceDisallowComma) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceDisallowComma) p.exitNode(node.AsNode(), state) } @@ -2960,13 +2960,13 @@ func (p *Printer) emitClassExpression(node *ast.ClassExpression) { indented := p.shouldEmitIndented(node.AsNode()) p.increaseIndentIf(indented) - p.emitTypeParameters(node.AsNode(), node.TypeParameters) - p.emitList((*Printer).emitHeritageClauseNode, node.AsNode(), node.HeritageClauses, LFClassHeritageClauses) + p.emitTypeParameters(node.AsNode(), node.TypeParameters()) + p.emitList((*Printer).emitHeritageClauseNode, node.AsNode(), node.HeritageClauses(), LFClassHeritageClauses) p.writeSpace() p.writePunctuation("{") p.pushNameGenerationScope(node.AsNode()) - p.generateAllMemberNames(node.Members) - p.emitList((*Printer).emitClassElement, node.AsNode(), node.Members, LFClassMembers) + p.generateAllMemberNames(node.Members()) + p.emitList((*Printer).emitClassElement, node.AsNode(), node.Members(), LFClassMembers) p.popNameGenerationScope(node.AsNode()) p.writePunctuation("}") @@ -2980,34 +2980,34 @@ func (p *Printer) emitOmittedExpression(node *ast.Node) { func (p *Printer) emitExpressionWithTypeArguments(node *ast.ExpressionWithTypeArguments) { state := p.enterNode(node.AsNode()) - p.emitExpression(node.Expression, ast.OperatorPrecedenceMember) - p.emitTypeArguments(node.AsNode(), node.TypeArguments) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceMember) + p.emitTypeArguments(node.AsNode(), node.TypeArguments()) p.exitNode(node.AsNode(), state) } func (p *Printer) emitAsExpression(node *ast.AsExpression) { state := p.enterNode(node.AsNode()) - p.emitExpression(node.Expression, ast.OperatorPrecedenceRelational) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceRelational) p.writeSpace() p.writeKeyword("as") p.writeSpace() - p.emitTypeNodeOutsideExtends(node.Type) + p.emitTypeNodeOutsideExtends(node.Type()) p.exitNode(node.AsNode(), state) } func (p *Printer) emitSatisfiesExpression(node *ast.SatisfiesExpression) { state := p.enterNode(node.AsNode()) - p.emitExpression(node.Expression, ast.OperatorPrecedenceRelational) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceRelational) p.writeSpace() p.writeKeyword("satisfies") p.writeSpace() - p.emitTypeNodeOutsideExtends(node.Type) + p.emitTypeNodeOutsideExtends(node.Type()) p.exitNode(node.AsNode(), state) } func (p *Printer) emitNonNullExpression(node *ast.NonNullExpression) { state := p.enterNode(node.AsNode()) - p.emitExpression(node.Expression, ast.OperatorPrecedenceMember) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceMember) p.writeOperator("!") p.exitNode(node.AsNode(), state) } @@ -3030,24 +3030,24 @@ func (p *Printer) emitPartiallyEmittedExpression(node *ast.PartiallyEmittedExpre for { state := p.enterNode(node.AsNode()) emitFlags := p.emitContext.EmitFlags(node.AsNode()) - if emitFlags&EFNoLeadingComments == 0 && node.Pos() != node.Expression.Pos() { - p.emitTrailingCommentsOfPosition(node.Expression.Pos(), false /*prefixSpace*/, false /*forceNoNewline*/) + if emitFlags&EFNoLeadingComments == 0 && node.Pos() != node.Expression().Pos() { + p.emitTrailingCommentsOfPosition(node.Expression().Pos(), false /*prefixSpace*/, false /*forceNoNewline*/) } stack.Push(entry{node, state}) - if !ast.IsPartiallyEmittedExpression(node.Expression) { + if !ast.IsPartiallyEmittedExpression(node.Expression()) { break } - node = node.Expression.AsPartiallyEmittedExpression() + node = node.Expression().AsPartiallyEmittedExpression() } - p.emitExpression(node.Expression, ast.OperatorPrecedenceLowest) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceLowest) // unwind stack for stack.Len() > 0 { entry := stack.Pop() emitFlags := p.emitContext.EmitFlags(node.AsNode()) - if emitFlags&EFNoTrailingComments == 0 && node.End() != node.Expression.End() { - p.emitLeadingCommentsOfPosition(node.Expression.End()) + if emitFlags&EFNoTrailingComments == 0 && node.End() != node.Expression().End() { + p.emitLeadingCommentsOfPosition(node.Expression().End()) } p.exitNode(node.AsNode(), entry.state) node = entry.node @@ -3076,7 +3076,7 @@ func (p *Printer) willEmitLeadingNewLine(node *ast.Expression) bool { } if hasLeadingCommentRanges { parseNode := p.emitContext.ParseNode(node) - if parseNode != nil && ast.IsParenthesizedExpression(parseNode.Parent) { + if parseNode != nil && ast.IsParenthesizedExpression(parseNode.Parent()) { return true } } @@ -3088,14 +3088,14 @@ func (p *Printer) willEmitLeadingNewLine(node *ast.Expression) bool { } if ast.IsPartiallyEmittedExpression(node) { pee := node.AsPartiallyEmittedExpression() - if node.Pos() != pee.Expression.Pos() { - for comment := range scanner.GetTrailingCommentRanges(p.emitContext.Factory.AsNodeFactory(), p.currentSourceFile.Text(), pee.Expression.Pos()) { + if node.Pos() != pee.Expression().Pos() { + for comment := range scanner.GetTrailingCommentRanges(p.emitContext.Factory.AsNodeFactory(), p.currentSourceFile.Text(), pee.Expression().Pos()) { if p.commentWillEmitNewLine(comment) { return true } } } - return p.willEmitLeadingNewLine(pee.Expression) + return p.willEmitLeadingNewLine(pee.Expression()) } return false } @@ -3111,7 +3111,7 @@ func (p *Printer) parenthesizeExpressionForNoAsi(node *ast.Expression) *ast.Expr parseNode := p.emitContext.ParseNode(node) if parseNode != nil && ast.IsParenthesizedExpression(parseNode) { // If the original node was a parenthesized expression, restore it to preserve comment and source map emit - parens := p.emitContext.Factory.NewParenthesizedExpression(pee.Expression) + parens := p.emitContext.Factory.NewParenthesizedExpression(pee.Expression()) p.emitContext.SetOriginal(parens, node) parens.Loc = parseNode.Loc return parens @@ -3121,14 +3121,14 @@ func (p *Printer) parenthesizeExpressionForNoAsi(node *ast.Expression) *ast.Expr pee := node.AsPartiallyEmittedExpression() return p.emitContext.Factory.UpdatePartiallyEmittedExpression( pee, - p.parenthesizeExpressionForNoAsi(pee.Expression), + p.parenthesizeExpressionForNoAsi(pee.Expression()), ) case ast.KindPropertyAccessExpression: pae := node.AsPropertyAccessExpression() return p.emitContext.Factory.UpdatePropertyAccessExpression( pae, - p.parenthesizeExpressionForNoAsi(pae.Expression), - pae.QuestionDotToken, + p.parenthesizeExpressionForNoAsi(pae.Expression()), + pae.QuestionDotToken(), pae.Name(), pae.Flags, ) @@ -3136,36 +3136,36 @@ func (p *Printer) parenthesizeExpressionForNoAsi(node *ast.Expression) *ast.Expr eae := node.AsElementAccessExpression() return p.emitContext.Factory.UpdateElementAccessExpression( eae, - p.parenthesizeExpressionForNoAsi(eae.Expression), - eae.QuestionDotToken, - eae.ArgumentExpression, + p.parenthesizeExpressionForNoAsi(eae.Expression()), + eae.QuestionDotToken(), + eae.ArgumentExpression(), eae.Flags, ) case ast.KindCallExpression: ce := node.AsCallExpression() return p.emitContext.Factory.UpdateCallExpression( ce, - p.parenthesizeExpressionForNoAsi(ce.Expression), - ce.QuestionDotToken, - ce.TypeArguments, - ce.Arguments, + p.parenthesizeExpressionForNoAsi(ce.Expression()), + ce.QuestionDotToken(), + ce.TypeArguments(), + ce.Arguments(), ce.Flags, ) case ast.KindTaggedTemplateExpression: tte := node.AsTaggedTemplateExpression() return p.emitContext.Factory.UpdateTaggedTemplateExpression( tte, - p.parenthesizeExpressionForNoAsi(tte.Tag), - tte.QuestionDotToken, - tte.TypeArguments, - tte.Template, + p.parenthesizeExpressionForNoAsi(tte.Tag()), + tte.QuestionDotToken(), + tte.TypeArguments(), + tte.Template(), tte.Flags, ) case ast.KindPostfixUnaryExpression: pue := node.AsPostfixUnaryExpression() return p.emitContext.Factory.UpdatePostfixUnaryExpression( pue, - p.parenthesizeExpressionForNoAsi(pue.Operand), + p.parenthesizeExpressionForNoAsi(pue.Operand()), pue.Operator, ) case ast.KindBinaryExpression: @@ -3173,40 +3173,40 @@ func (p *Printer) parenthesizeExpressionForNoAsi(node *ast.Expression) *ast.Expr return p.emitContext.Factory.UpdateBinaryExpression( be, be.Modifiers(), - p.parenthesizeExpressionForNoAsi(be.Left), - be.Type, - be.OperatorToken, - be.Right, + p.parenthesizeExpressionForNoAsi(be.Left()), + be.Type(), + be.OperatorToken(), + be.Right(), ) case ast.KindConditionalExpression: ce := node.AsConditionalExpression() return p.emitContext.Factory.UpdateConditionalExpression( ce, - p.parenthesizeExpressionForNoAsi(ce.Condition), - ce.QuestionToken, - ce.WhenTrue, - ce.ColonToken, - ce.WhenFalse, + p.parenthesizeExpressionForNoAsi(ce.Condition()), + ce.QuestionToken(), + ce.WhenTrue(), + ce.ColonToken(), + ce.WhenFalse(), ) case ast.KindAsExpression: ae := node.AsAsExpression() return p.emitContext.Factory.UpdateAsExpression( ae, - p.parenthesizeExpressionForNoAsi(ae.Expression), - ae.Type, + p.parenthesizeExpressionForNoAsi(ae.Expression()), + ae.Type(), ) case ast.KindSatisfiesExpression: se := node.AsSatisfiesExpression() return p.emitContext.Factory.UpdateSatisfiesExpression( se, - p.parenthesizeExpressionForNoAsi(se.Expression), - se.Type, + p.parenthesizeExpressionForNoAsi(se.Expression()), + se.Type(), ) case ast.KindNonNullExpression: nne := node.AsNonNullExpression() return p.emitContext.Factory.UpdateNonNullExpression( nne, - p.parenthesizeExpressionForNoAsi(nne.Expression), + p.parenthesizeExpressionForNoAsi(nne.Expression()), nne.Flags, ) } @@ -3349,8 +3349,8 @@ func (p *Printer) emitExpression(node *ast.Expression, precedence ast.OperatorPr func (p *Printer) emitTemplateSpan(node *ast.TemplateSpan) { state := p.enterNode(node.AsNode()) - p.emitExpression(node.Expression, ast.OperatorPrecedenceComma) - p.emitTemplateMiddleTail(node.Literal) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceComma) + p.emitTemplateMiddleTail(node.Literal()) p.exitNode(node.AsNode(), state) } @@ -3378,19 +3378,19 @@ func (p *Printer) emitBlock(node *ast.Block) { p.generateNames(node.AsNode()) p.emitToken(ast.KindOpenBraceToken, node.Pos(), WriteKindPunctuation, node.AsNode()) - format := core.IfElse(!node.MultiLine && p.isEmptyBlock(node.AsNode(), node.Statements) || p.shouldEmitOnSingleLine(node.AsNode()), + format := core.IfElse(!node.MultiLine && p.isEmptyBlock(node.AsNode(), node.Statements()) || p.shouldEmitOnSingleLine(node.AsNode()), LFSingleLineBlockStatements, LFMultiLineBlockStatements) - p.emitList((*Printer).emitStatement, node.AsNode(), node.Statements, format) + p.emitList((*Printer).emitStatement, node.AsNode(), node.Statements(), format) - p.emitTokenEx(ast.KindCloseBraceToken, node.Statements.End(), WriteKindPunctuation, node.AsNode(), core.IfElse(format&LFMultiLine != 0, tefIndentLeadingComments, tefNone)) + p.emitTokenEx(ast.KindCloseBraceToken, node.Statements().End(), WriteKindPunctuation, node.AsNode(), core.IfElse(format&LFMultiLine != 0, tefIndentLeadingComments, tefNone)) p.exitNode(node.AsNode(), state) } func (p *Printer) emitVariableStatement(node *ast.VariableStatement) { state := p.enterNode(node.AsNode()) p.emitModifierList(node.AsNode(), node.Modifiers(), false /*allowDecorators*/) - p.emitVariableDeclarationList(node.DeclarationList.AsVariableDeclarationList()) + p.emitVariableDeclarationList(node.DeclarationList().AsVariableDeclarationList()) p.writeTrailingSemicolon() p.exitNode(node.AsNode(), state) } @@ -3413,18 +3413,18 @@ func (p *Printer) emitExpressionStatement(node *ast.ExpressionStatement) { if p.currentSourceFile != nil && p.currentSourceFile.ScriptKind == core.ScriptKindJSON { // !!! In strada, this was handled by an undefined parenthesizerRule, so this is a hack. - p.emitExpression(node.Expression, ast.OperatorPrecedenceComma) - } else if isImmediatelyInvokedFunctionExpressionOrArrowFunction(node.Expression) { + p.emitExpression(node.Expression(), ast.OperatorPrecedenceComma) + } else if isImmediatelyInvokedFunctionExpressionOrArrowFunction(node.Expression()) { // For IIFEs, parenthesize just the callee (not the whole call), matching TypeScript's // parenthesizeExpressionOfExpressionStatement which wraps the function/arrow in parens: // (function() { })() -- not (function() { }()) - p.emitIIFEWithParenthesizedCallee(node.Expression) + p.emitIIFEWithParenthesizedCallee(node.Expression()) } else { - switch ast.GetLeftmostExpression(node.Expression, false /*stopAtCallExpression*/).Kind { + switch ast.GetLeftmostExpression(node.Expression(), false /*stopAtCallExpression*/).Kind { case ast.KindFunctionExpression, ast.KindObjectLiteralExpression: - p.emitExpression(node.Expression, ast.OperatorPrecedenceParentheses) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceParentheses) default: - p.emitExpression(node.Expression, ast.OperatorPrecedenceComma) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceComma) } } @@ -3432,7 +3432,7 @@ func (p *Printer) emitExpressionStatement(node *ast.ExpressionStatement) { // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) if p.currentSourceFile == nil || p.currentSourceFile.ScriptKind != core.ScriptKindJSON || - ast.NodeIsSynthesized(node.Expression) { + ast.NodeIsSynthesized(node.Expression()) { p.writeTrailingSemicolon() } @@ -3454,11 +3454,11 @@ func (p *Printer) emitIIFEWithParenthesizedCallee(node *ast.Expression) { state := p.enterNode(call.AsNode()) // Emit the callee wrapped in parens p.writePunctuation("(") - p.emitExpression(call.Expression, ast.OperatorPrecedenceLowest) + p.emitExpression(call.Expression(), ast.OperatorPrecedenceLowest) p.writePunctuation(")") - p.emitTokenNode(call.QuestionDotToken) - p.emitTypeArguments(call.AsNode(), call.TypeArguments) - p.emitList((*Printer).emitArgument, call.AsNode(), call.Arguments, LFCallExpressionArguments) + p.emitTokenNode(call.QuestionDotToken()) + p.emitTypeArguments(call.AsNode(), call.TypeArguments()) + p.emitList((*Printer).emitArgument, call.AsNode(), call.Arguments(), LFCallExpressionArguments) p.exitNode(call.AsNode(), state) } @@ -3467,17 +3467,17 @@ func (p *Printer) emitIfStatement(node *ast.IfStatement) { pos := p.emitToken(ast.KindIfKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) p.writeSpace() p.emitToken(ast.KindOpenParenToken, pos, WriteKindPunctuation, node.AsNode()) - p.emitExpression(node.Expression, ast.OperatorPrecedenceLowest) - p.emitToken(ast.KindCloseParenToken, node.Expression.End(), WriteKindPunctuation, node.AsNode()) - p.emitEmbeddedStatement(node.AsNode(), node.ThenStatement) - if node.ElseStatement != nil { - p.writeLineOrSpace(node.AsNode(), node.ThenStatement, node.ElseStatement) - p.emitToken(ast.KindElseKeyword, node.ThenStatement.End(), WriteKindKeyword, node.AsNode()) - if node.ElseStatement.Kind == ast.KindIfStatement { + p.emitExpression(node.Expression(), ast.OperatorPrecedenceLowest) + p.emitToken(ast.KindCloseParenToken, node.Expression().End(), WriteKindPunctuation, node.AsNode()) + p.emitEmbeddedStatement(node.AsNode(), node.ThenStatement()) + if node.ElseStatement() != nil { + p.writeLineOrSpace(node.AsNode(), node.ThenStatement(), node.ElseStatement()) + p.emitToken(ast.KindElseKeyword, node.ThenStatement().End(), WriteKindKeyword, node.AsNode()) + if node.ElseStatement().Kind == ast.KindIfStatement { p.writeSpace() - p.emitIfStatement(node.ElseStatement.AsIfStatement()) + p.emitIfStatement(node.ElseStatement().AsIfStatement()) } else { - p.emitEmbeddedStatement(node.AsNode(), node.ElseStatement) + p.emitEmbeddedStatement(node.AsNode(), node.ElseStatement()) } } p.exitNode(node.AsNode(), state) @@ -3494,22 +3494,22 @@ func (p *Printer) emitWhileClause(node *ast.Node, expression *ast.Expression, st func (p *Printer) emitDoStatement(node *ast.DoStatement) { state := p.enterNode(node.AsNode()) p.emitToken(ast.KindDoKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) - p.emitEmbeddedStatement(node.AsNode(), node.Statement) - if ast.IsBlock(node.Statement) && !p.Options.PreserveSourceNewlines { + p.emitEmbeddedStatement(node.AsNode(), node.Statement()) + if ast.IsBlock(node.Statement()) && !p.Options.PreserveSourceNewlines { p.writeSpace() } else { - p.writeLineOrSpace(node.AsNode(), node.Statement, node.Expression) + p.writeLineOrSpace(node.AsNode(), node.Statement(), node.Expression()) } - p.emitWhileClause(node.AsNode(), node.Expression, node.Statement.End()) + p.emitWhileClause(node.AsNode(), node.Expression(), node.Statement().End()) p.writeTrailingSemicolon() p.exitNode(node.AsNode(), state) } func (p *Printer) emitWhileStatement(node *ast.WhileStatement) { state := p.enterNode(node.AsNode()) - p.emitWhileClause(node.AsNode(), node.Expression, node.Pos()) - p.emitEmbeddedStatement(node.AsNode(), node.Statement) + p.emitWhileClause(node.AsNode(), node.Expression(), node.Pos()) + p.emitEmbeddedStatement(node.AsNode(), node.Statement()) p.exitNode(node.AsNode(), state) } @@ -3526,24 +3526,24 @@ func (p *Printer) emitForStatement(node *ast.ForStatement) { pos := p.emitToken(ast.KindForKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) p.writeSpace() pos = p.emitToken(ast.KindOpenParenToken, pos, WriteKindPunctuation, node.AsNode()) - if node.Initializer != nil { - p.emitForInitializer(node.Initializer) - pos = node.Initializer.End() + if node.Initializer() != nil { + p.emitForInitializer(node.Initializer()) + pos = node.Initializer().End() } pos = p.emitToken(ast.KindSemicolonToken, pos, WriteKindPunctuation, node.AsNode()) - if node.Condition != nil { + if node.Condition() != nil { p.writeSpace() - p.emitExpression(node.Condition, ast.OperatorPrecedenceLowest) - pos = node.Condition.End() + p.emitExpression(node.Condition(), ast.OperatorPrecedenceLowest) + pos = node.Condition().End() } pos = p.emitToken(ast.KindSemicolonToken, pos, WriteKindPunctuation, node.AsNode()) - if node.Incrementor != nil { + if node.Incrementor() != nil { p.writeSpace() - p.emitExpression(node.Incrementor, ast.OperatorPrecedenceLowest) - pos = node.Incrementor.End() + p.emitExpression(node.Incrementor(), ast.OperatorPrecedenceLowest) + pos = node.Incrementor().End() } p.emitToken(ast.KindCloseParenToken, pos, WriteKindPunctuation, node.AsNode()) - p.emitEmbeddedStatement(node.AsNode(), node.Statement) + p.emitEmbeddedStatement(node.AsNode(), node.Statement()) p.exitNode(node.AsNode(), state) } @@ -3552,13 +3552,13 @@ func (p *Printer) emitForInStatement(node *ast.ForInOrOfStatement) { pos := p.emitToken(ast.KindForKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) p.writeSpace() p.emitToken(ast.KindOpenParenToken, pos, WriteKindPunctuation, node.AsNode()) - p.emitForInitializer(node.Initializer) + p.emitForInitializer(node.Initializer()) p.writeSpace() - p.emitToken(ast.KindInKeyword, node.Initializer.End(), WriteKindKeyword, node.AsNode()) + p.emitToken(ast.KindInKeyword, node.Initializer().End(), WriteKindKeyword, node.AsNode()) p.writeSpace() - p.emitExpression(node.Expression, ast.OperatorPrecedenceLowest) - p.emitToken(ast.KindCloseParenToken, node.Expression.End(), WriteKindPunctuation, node.AsNode()) - p.emitEmbeddedStatement(node.AsNode(), node.Statement) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceLowest) + p.emitToken(ast.KindCloseParenToken, node.Expression().End(), WriteKindPunctuation, node.AsNode()) + p.emitEmbeddedStatement(node.AsNode(), node.Statement()) p.exitNode(node.AsNode(), state) } @@ -3566,27 +3566,27 @@ func (p *Printer) emitForOfStatement(node *ast.ForInOrOfStatement) { state := p.enterNode(node.AsNode()) openParenPos := p.emitToken(ast.KindForKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) p.writeSpace() - if node.AwaitModifier != nil { - p.emitKeywordNode(node.AwaitModifier) + if node.AwaitModifier() != nil { + p.emitKeywordNode(node.AwaitModifier()) p.writeSpace() } p.emitToken(ast.KindOpenParenToken, openParenPos, WriteKindPunctuation, node.AsNode()) - p.emitForInitializer(node.Initializer) + p.emitForInitializer(node.Initializer()) p.writeSpace() - p.emitToken(ast.KindOfKeyword, node.Initializer.End(), WriteKindKeyword, node.AsNode()) + p.emitToken(ast.KindOfKeyword, node.Initializer().End(), WriteKindKeyword, node.AsNode()) p.writeSpace() - p.emitExpression(node.Expression, ast.OperatorPrecedenceLowest) - p.emitToken(ast.KindCloseParenToken, node.Expression.End(), WriteKindPunctuation, node.AsNode()) - p.emitEmbeddedStatement(node.AsNode(), node.Statement) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceLowest) + p.emitToken(ast.KindCloseParenToken, node.Expression().End(), WriteKindPunctuation, node.AsNode()) + p.emitEmbeddedStatement(node.AsNode(), node.Statement()) p.exitNode(node.AsNode(), state) } func (p *Printer) emitContinueStatement(node *ast.ContinueStatement) { state := p.enterNode(node.AsNode()) p.emitToken(ast.KindContinueKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) - if node.Label != nil { + if node.Label() != nil { p.writeSpace() - p.emitLabelIdentifier(node.Label.AsIdentifier()) + p.emitLabelIdentifier(node.Label().AsIdentifier()) } p.writeTrailingSemicolon() p.exitNode(node.AsNode(), state) @@ -3595,9 +3595,9 @@ func (p *Printer) emitContinueStatement(node *ast.ContinueStatement) { func (p *Printer) emitBreakStatement(node *ast.BreakStatement) { state := p.enterNode(node.AsNode()) p.emitToken(ast.KindBreakKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) - if node.Label != nil { + if node.Label() != nil { p.writeSpace() - p.emitLabelIdentifier(node.Label.AsIdentifier()) + p.emitLabelIdentifier(node.Label().AsIdentifier()) } p.writeTrailingSemicolon() p.exitNode(node.AsNode(), state) @@ -3606,9 +3606,9 @@ func (p *Printer) emitBreakStatement(node *ast.BreakStatement) { func (p *Printer) emitReturnStatement(node *ast.ReturnStatement) { state := p.enterNode(node.AsNode()) p.emitToken(ast.KindReturnKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) - if node.Expression != nil { + if node.Expression() != nil { p.writeSpace() - p.emitExpressionNoASI(node.Expression, ast.OperatorPrecedenceLowest) + p.emitExpressionNoASI(node.Expression(), ast.OperatorPrecedenceLowest) } p.writeTrailingSemicolon() p.exitNode(node.AsNode(), state) @@ -3619,9 +3619,9 @@ func (p *Printer) emitWithStatement(node *ast.WithStatement) { pos := p.emitToken(ast.KindWithKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) p.writeSpace() p.emitToken(ast.KindOpenParenToken, pos, WriteKindPunctuation, node.AsNode()) - p.emitExpression(node.Expression, ast.OperatorPrecedenceLowest) - p.emitToken(ast.KindCloseParenToken, node.Expression.End(), WriteKindPunctuation, node.AsNode()) - p.emitEmbeddedStatement(node.AsNode(), node.Statement) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceLowest) + p.emitToken(ast.KindCloseParenToken, node.Expression().End(), WriteKindPunctuation, node.AsNode()) + p.emitEmbeddedStatement(node.AsNode(), node.Statement()) p.exitNode(node.AsNode(), state) } @@ -3630,17 +3630,17 @@ func (p *Printer) emitSwitchStatement(node *ast.SwitchStatement) { pos := p.emitToken(ast.KindSwitchKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) p.writeSpace() p.emitToken(ast.KindOpenParenToken, pos, WriteKindPunctuation, node.AsNode()) - p.emitExpression(node.Expression, ast.OperatorPrecedenceLowest) - p.emitToken(ast.KindCloseParenToken, node.Expression.End(), WriteKindPunctuation, node.AsNode()) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceLowest) + p.emitToken(ast.KindCloseParenToken, node.Expression().End(), WriteKindPunctuation, node.AsNode()) p.writeSpace() - p.emitCaseBlock(node.CaseBlock.AsCaseBlock()) + p.emitCaseBlock(node.CaseBlock().AsCaseBlock()) p.exitNode(node.AsNode(), state) } func (p *Printer) emitLabeledStatement(node *ast.LabeledStatement) { state := p.enterNode(node.AsNode()) - p.emitLabelIdentifier(node.Label.AsIdentifier()) - p.emitToken(ast.KindColonToken, node.Label.End(), WriteKindPunctuation, node.AsNode()) + p.emitLabelIdentifier(node.Label().AsIdentifier()) + p.emitToken(ast.KindColonToken, node.Label().End(), WriteKindPunctuation, node.AsNode()) // TODO: use emitEmbeddedStatement rather than writeSpace/emitStatement here after Strada migration as it is // more consistent with similar emit elsewhere. writeSpace/emitStatement is used here to reduce spurious @@ -3648,7 +3648,7 @@ func (p *Printer) emitLabeledStatement(node *ast.LabeledStatement) { ////p.emitEmbeddedStatement(node.AsNode(), node.Statement) p.writeSpace() - p.emitStatement(node.Statement) + p.emitStatement(node.Statement()) p.exitNode(node.AsNode(), state) } @@ -3657,7 +3657,7 @@ func (p *Printer) emitThrowStatement(node *ast.ThrowStatement) { state := p.enterNode(node.AsNode()) p.emitToken(ast.KindThrowKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) p.writeSpace() - p.emitExpressionNoASI(node.Expression, ast.OperatorPrecedenceLowest) + p.emitExpressionNoASI(node.Expression(), ast.OperatorPrecedenceLowest) p.writeTrailingSemicolon() p.exitNode(node.AsNode(), state) } @@ -3666,16 +3666,16 @@ func (p *Printer) emitTryStatement(node *ast.TryStatement) { state := p.enterNode(node.AsNode()) p.emitToken(ast.KindTryKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) p.writeSpace() - p.emitBlock(node.TryBlock.AsBlock()) - if node.CatchClause != nil { - p.writeLineOrSpace(node.AsNode(), node.TryBlock, node.CatchClause) - p.emitCatchClause(node.CatchClause.AsCatchClause()) - } - if node.FinallyBlock != nil { - p.writeLineOrSpace(node.AsNode(), core.Coalesce(node.CatchClause, node.TryBlock), node.FinallyBlock) - p.emitToken(ast.KindFinallyKeyword, core.Coalesce(node.CatchClause, node.TryBlock).End(), WriteKindKeyword, node.AsNode()) + p.emitBlock(node.TryBlock().AsBlock()) + if node.CatchClause() != nil { + p.writeLineOrSpace(node.AsNode(), node.TryBlock(), node.CatchClause()) + p.emitCatchClause(node.CatchClause().AsCatchClause()) + } + if node.FinallyBlock() != nil { + p.writeLineOrSpace(node.AsNode(), core.Coalesce(node.CatchClause(), node.TryBlock()), node.FinallyBlock()) + p.emitToken(ast.KindFinallyKeyword, core.Coalesce(node.CatchClause(), node.TryBlock()).End(), WriteKindKeyword, node.AsNode()) p.writeSpace() - p.emitBlock(node.FinallyBlock.AsBlock()) + p.emitBlock(node.FinallyBlock().AsBlock()) } p.exitNode(node.AsNode(), state) } @@ -3702,9 +3702,9 @@ func (p *Printer) emitNotEmittedTypeElement(node *ast.NotEmittedTypeElement) { func (p *Printer) emitVariableDeclaration(node *ast.VariableDeclaration) { state := p.enterNode(node.AsNode()) p.emitBindingName(node.Name()) - p.emitPunctuationNode(node.ExclamationToken) - p.emitTypeAnnotation(node.Type) - p.emitInitializer(node.Initializer, greatestEnd(node.Name().End(), node.Type, p.emitContext.GetTypeNode(node.Name())), node.AsNode()) + p.emitPunctuationNode(node.ExclamationToken()) + p.emitTypeAnnotation(node.Type()) + p.emitInitializer(node.Initializer(), greatestEnd(node.Name().End(), node.Type(), p.emitContext.GetTypeNode(node.Name())), node.AsNode()) p.exitNode(node.AsNode(), state) } @@ -3729,7 +3729,7 @@ func (p *Printer) emitVariableDeclarationList(node *ast.VariableDeclarationList) p.writeKeyword("var") } p.writeSpace() - p.emitList((*Printer).emitVariableDeclarationNode, node.AsNode(), node.Declarations, LFVariableDeclarationList) + p.emitList((*Printer).emitVariableDeclarationNode, node.AsNode(), node.Declarations(), LFVariableDeclarationList) p.exitNode(node.AsNode(), state) } @@ -3738,7 +3738,7 @@ func (p *Printer) emitFunctionDeclaration(node *ast.FunctionDeclaration) { p.generateNameIfNeeded(node.Name()) p.emitModifierList(node.AsNode(), node.Modifiers(), false /*allowDecorators*/) p.writeKeyword("function") - p.emitTokenNode(node.AsteriskToken) + p.emitTokenNode(node.AsteriskToken()) p.writeSpace() if name := node.Name(); name != nil { p.emitIdentifierName(name.AsIdentifier()) @@ -3747,7 +3747,7 @@ func (p *Printer) emitFunctionDeclaration(node *ast.FunctionDeclaration) { p.increaseIndentIf(indented) p.pushNameGenerationScope(node.AsNode()) p.emitSignature(node.AsNode()) - p.emitFunctionBodyNode(node.Body) + p.emitFunctionBodyNode(node.Body()) p.popNameGenerationScope(node.AsNode()) p.decreaseIndentIf(indented) p.exitNode(node.AsNode(), state) @@ -3764,13 +3764,13 @@ func (p *Printer) emitClassDeclaration(node *ast.ClassDeclaration) { } indented := p.shouldEmitIndented(node.AsNode()) p.increaseIndentIf(indented) - p.emitTypeParameters(node.AsNode(), node.TypeParameters) - p.emitList((*Printer).emitHeritageClauseNode, node.AsNode(), node.HeritageClauses, LFClassHeritageClauses) + p.emitTypeParameters(node.AsNode(), node.TypeParameters()) + p.emitList((*Printer).emitHeritageClauseNode, node.AsNode(), node.HeritageClauses(), LFClassHeritageClauses) p.writeSpace() p.writePunctuation("{") p.pushNameGenerationScope(node.AsNode()) - p.generateAllMemberNames(node.Members) - p.emitList((*Printer).emitClassElement, node.AsNode(), node.Members, LFClassMembers) + p.generateAllMemberNames(node.Members()) + p.emitList((*Printer).emitClassElement, node.AsNode(), node.Members(), LFClassMembers) p.popNameGenerationScope(node.AsNode()) p.writePunctuation("}") p.decreaseIndentIf(indented) @@ -3783,13 +3783,13 @@ func (p *Printer) emitInterfaceDeclaration(node *ast.InterfaceDeclaration) { p.writeKeyword("interface") p.writeSpace() p.emitBindingIdentifier(node.Name().AsIdentifier()) - p.emitTypeParameters(node.AsNode(), node.TypeParameters) - p.emitList((*Printer).emitHeritageClauseNode, node.AsNode(), node.HeritageClauses, LFHeritageClauses) + p.emitTypeParameters(node.AsNode(), node.TypeParameters()) + p.emitList((*Printer).emitHeritageClauseNode, node.AsNode(), node.HeritageClauses(), LFHeritageClauses) p.writeSpace() p.writePunctuation("{") p.pushNameGenerationScope(node.AsNode()) - p.generateAllMemberNames(node.Members) - p.emitList((*Printer).emitTypeElement, node.AsNode(), node.Members, LFInterfaceMembers) + p.generateAllMemberNames(node.Members()) + p.emitList((*Printer).emitTypeElement, node.AsNode(), node.Members(), LFInterfaceMembers) p.popNameGenerationScope(node.AsNode()) p.writePunctuation("}") p.exitNode(node.AsNode(), state) @@ -3801,11 +3801,11 @@ func (p *Printer) emitTypeAliasDeclaration(node *ast.TypeAliasDeclaration) { p.writeKeyword("type") p.writeSpace() p.emitBindingIdentifier(node.Name().AsIdentifier()) - p.emitTypeParameters(node.AsNode(), node.TypeParameters) + p.emitTypeParameters(node.AsNode(), node.TypeParameters()) p.writeSpace() p.writePunctuation("=") p.writeSpace() - p.emitTypeNodeOutsideExtends(node.Type) + p.emitTypeNodeOutsideExtends(node.Type()) p.writeTrailingSemicolon() p.exitNode(node.AsNode(), state) } @@ -3818,7 +3818,7 @@ func (p *Printer) emitEnumDeclaration(node *ast.EnumDeclaration) { p.emitBindingIdentifier(node.Name().AsIdentifier()) p.writeSpace() p.writePunctuation("{") - p.emitList((*Printer).emitEnumMemberNode, node.AsNode(), node.Members, LFEnumMembers) + p.emitList((*Printer).emitEnumMemberNode, node.AsNode(), node.Members(), LFEnumMembers) p.writePunctuation("}") p.exitNode(node.AsNode(), state) } @@ -3831,18 +3831,18 @@ func (p *Printer) emitModuleDeclaration(node *ast.ModuleDeclaration) { p.writeSpace() } p.emitModuleName(node.Name()) - body := node.Body + body := node.Body() for body != nil && ast.IsModuleDeclaration(body) { module := body.AsModuleDeclaration() p.writePunctuation(".") p.emitNestedModuleName(module.Name()) - body = module.Body + body = module.Body() } - if node.Attributes != nil { + if node.Attributes() != nil { p.writeSpace() p.writeKeyword("with") p.writeSpace() - p.emitTypeNode(node.Attributes, ast.TypePrecedenceNonArray) + p.emitTypeNode(node.Attributes(), ast.TypePrecedenceNonArray) } if body == nil { p.writeTrailingSemicolon() @@ -3857,19 +3857,19 @@ func (p *Printer) emitModuleBlock(node *ast.ModuleBlock) { state := p.enterNode(node.AsNode()) p.generateNames(node.AsNode()) p.emitToken(ast.KindOpenBraceToken, node.Pos(), WriteKindPunctuation, node.AsNode()) - format := core.IfElse(p.isEmptyBlock(node.AsNode(), node.Statements) || p.shouldEmitOnSingleLine(node.AsNode()), + format := core.IfElse(p.isEmptyBlock(node.AsNode(), node.Statements()) || p.shouldEmitOnSingleLine(node.AsNode()), LFSingleLineBlockStatements, LFMultiLineBlockStatements) - p.emitList((*Printer).emitStatement, node.AsNode(), node.Statements, format) - p.emitTokenEx(ast.KindCloseBraceToken, node.Statements.End(), WriteKindPunctuation, node.AsNode(), core.IfElse(format&LFMultiLine != 0, tefIndentLeadingComments, tefNone)) + p.emitList((*Printer).emitStatement, node.AsNode(), node.Statements(), format) + p.emitTokenEx(ast.KindCloseBraceToken, node.Statements().End(), WriteKindPunctuation, node.AsNode(), core.IfElse(format&LFMultiLine != 0, tefIndentLeadingComments, tefNone)) p.exitNode(node.AsNode(), state) } func (p *Printer) emitCaseBlock(node *ast.CaseBlock) { state := p.enterNode(node.AsNode()) p.emitToken(ast.KindOpenBraceToken, node.Pos(), WriteKindPunctuation, node.AsNode()) - p.emitList((*Printer).emitCaseOrDefaultClauseNode, node.AsNode(), node.Clauses, LFCaseBlockClauses) - p.emitTokenEx(ast.KindCloseBraceToken, node.Clauses.End(), WriteKindPunctuation, node.AsNode(), tefIndentLeadingComments) + p.emitList((*Printer).emitCaseOrDefaultClauseNode, node.AsNode(), node.Clauses(), LFCaseBlockClauses) + p.emitTokenEx(ast.KindCloseBraceToken, node.Clauses().End(), WriteKindPunctuation, node.AsNode(), tefIndentLeadingComments) p.exitNode(node.AsNode(), state) } @@ -3886,7 +3886,7 @@ func (p *Printer) emitImportEqualsDeclaration(node *ast.ImportEqualsDeclaration) p.writeSpace() p.emitToken(ast.KindEqualsToken, node.Name().End(), WriteKindPunctuation, node.AsNode()) p.writeSpace() - p.emitModuleReference(node.ModuleReference) + p.emitModuleReference(node.ModuleReference()) p.writeTrailingSemicolon() p.exitNode(node.AsNode(), state) } @@ -3909,16 +3909,16 @@ func (p *Printer) emitImportDeclaration(node *ast.ImportDeclaration) { p.emitModifierList(node.AsNode(), node.Modifiers(), false /*allowDecorators*/) p.emitToken(ast.KindImportKeyword, greatestEnd(node.Pos(), node.Modifiers()), WriteKindKeyword, node.AsNode()) p.writeSpace() - if node.ImportClause != nil { - p.emitImportClause(node.ImportClause.AsImportClause()) + if node.ImportClause() != nil { + p.emitImportClause(node.ImportClause().AsImportClause()) p.writeSpace() - p.emitToken(ast.KindFromKeyword, node.ImportClause.End(), WriteKindKeyword, node.AsNode()) + p.emitToken(ast.KindFromKeyword, node.ImportClause().End(), WriteKindKeyword, node.AsNode()) p.writeSpace() } - p.emitExpression(node.ModuleSpecifier, ast.OperatorPrecedenceLowest) - if node.Attributes != nil { + p.emitExpression(node.ModuleSpecifier(), ast.OperatorPrecedenceLowest) + if node.Attributes() != nil { p.writeSpace() - p.emitImportAttributes(node.Attributes.AsImportAttributes()) + p.emitImportAttributes(node.Attributes().AsImportAttributes()) } p.writeTrailingSemicolon() p.exitNode(node.AsNode(), state) @@ -3932,12 +3932,12 @@ func (p *Printer) emitImportClause(node *ast.ImportClause) { } if name := node.Name(); name != nil { p.emitBindingIdentifier(node.Name().AsIdentifier()) - if node.NamedBindings != nil { + if node.NamedBindings() != nil { p.emitToken(ast.KindCommaToken, name.End(), WriteKindPunctuation, node.AsNode()) p.writeSpace() } } - p.emitNamedImportBindings(node.NamedBindings) + p.emitNamedImportBindings(node.NamedBindings()) p.exitNode(node.AsNode(), state) } @@ -3954,7 +3954,7 @@ func (p *Printer) emitNamespaceImport(node *ast.NamespaceImport) { func (p *Printer) emitNamedImports(node *ast.NamedImports) { state := p.enterNode(node.AsNode()) p.writePunctuation("{") - p.emitList((*Printer).emitImportSpecifierNode, node.AsNode(), node.Elements, LFNamedImportsOrExportsElements) + p.emitList((*Printer).emitImportSpecifierNode, node.AsNode(), node.Elements(), LFNamedImportsOrExportsElements) p.writePunctuation("}") p.exitNode(node.AsNode(), state) } @@ -3979,10 +3979,10 @@ func (p *Printer) emitImportSpecifier(node *ast.ImportSpecifier) { p.writeKeyword("type") p.writeSpace() } - if node.PropertyName != nil { - p.emitModuleExportName(node.PropertyName) + if node.PropertyName() != nil { + p.emitModuleExportName(node.PropertyName()) p.writeSpace() - p.emitToken(ast.KindAsKeyword, node.PropertyName.End(), WriteKindKeyword, node.AsNode()) + p.emitToken(ast.KindAsKeyword, node.PropertyName().End(), WriteKindKeyword, node.AsNode()) p.writeSpace() } p.emitBindingIdentifier(node.Name().AsIdentifier()) @@ -4004,14 +4004,14 @@ func (p *Printer) emitExportAssignment(node *ast.ExportAssignment) { } p.writeSpace() if node.IsExportEquals { - p.emitExpression(node.Expression, ast.OperatorPrecedenceAssignment) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceAssignment) } else { // parenthesize `class` and `function` expressions so as not to conflict with exported `class` and `function` declarations - expr := ast.GetLeftmostExpression(node.Expression, false /*stopAtCallExpressions*/) + expr := ast.GetLeftmostExpression(node.Expression(), false /*stopAtCallExpressions*/) if ast.IsClassExpression(expr) || ast.IsFunctionExpression(expr) { - p.emitExpression(node.Expression, ast.OperatorPrecedenceParentheses) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceParentheses) } else { - p.emitExpression(node.Expression, ast.OperatorPrecedenceAssignment) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceAssignment) } } p.writeTrailingSemicolon() @@ -4027,20 +4027,20 @@ func (p *Printer) emitExportDeclaration(node *ast.ExportDeclaration) { pos = p.emitToken(ast.KindTypeKeyword, pos, WriteKindKeyword, node.AsNode()) p.writeSpace() } - if node.ExportClause != nil { - p.emitNamedExportBindings(node.ExportClause) + if node.ExportClause() != nil { + p.emitNamedExportBindings(node.ExportClause()) } else { pos = p.emitToken(ast.KindAsteriskToken, pos, WriteKindPunctuation, node.AsNode()) } - if node.ModuleSpecifier != nil { + if node.ModuleSpecifier() != nil { p.writeSpace() - p.emitToken(ast.KindFromKeyword, greatestEnd(pos, node.ExportClause), WriteKindKeyword, node.AsNode()) + p.emitToken(ast.KindFromKeyword, greatestEnd(pos, node.ExportClause()), WriteKindKeyword, node.AsNode()) p.writeSpace() - p.emitExpression(node.ModuleSpecifier, ast.OperatorPrecedenceLowest) + p.emitExpression(node.ModuleSpecifier(), ast.OperatorPrecedenceLowest) } - if node.Attributes != nil { + if node.Attributes() != nil { p.writeSpace() - p.emitImportAttributes(node.Attributes.AsImportAttributes()) + p.emitImportAttributes(node.Attributes().AsImportAttributes()) } p.writeTrailingSemicolon() p.exitNode(node.AsNode(), state) @@ -4050,7 +4050,7 @@ func (p *Printer) emitImportAttributes(node *ast.ImportAttributes) { state := p.enterNode(node.AsNode()) p.emitToken(node.Token, node.Pos(), WriteKindKeyword, node.AsNode()) p.writeSpace() - p.emitList((*Printer).emitImportAttributeNode, node.AsNode(), node.Attributes, LFImportAttributes) + p.emitList((*Printer).emitImportAttributeNode, node.AsNode(), node.Attributes(), LFImportAttributes) p.exitNode(node.AsNode(), state) } @@ -4059,8 +4059,8 @@ func (p *Printer) emitImportAttribute(node *ast.ImportAttribute) { p.emitImportAttributeName(node.Name()) p.writePunctuation(":") p.writeSpace() - value := node.Value - if p.emitContext.EmitFlags(node.Value)&EFNoLeadingComments == 0 { + value := node.Value() + if p.emitContext.EmitFlags(node.Value())&EFNoLeadingComments == 0 { commentRange := p.emitContext.CommentRange(value) p.emitTrailingComments(commentRange.Pos(), commentSeparatorAfter) } @@ -4098,7 +4098,7 @@ func (p *Printer) emitNamespaceExport(node *ast.NamespaceExport) { func (p *Printer) emitNamedExports(node *ast.NamedExports) { state := p.enterNode(node.AsNode()) p.writePunctuation("{") - p.emitList((*Printer).emitExportSpecifierNode, node.AsNode(), node.Elements, LFNamedImportsOrExportsElements) + p.emitList((*Printer).emitExportSpecifierNode, node.AsNode(), node.Elements(), LFNamedImportsOrExportsElements) p.writePunctuation("}") p.exitNode(node.AsNode(), state) } @@ -4120,10 +4120,10 @@ func (p *Printer) emitExportSpecifier(node *ast.ExportSpecifier) { p.writeKeyword("type") p.writeSpace() } - if node.PropertyName != nil { - p.emitModuleExportName(node.PropertyName) + if node.PropertyName() != nil { + p.emitModuleExportName(node.PropertyName()) p.writeSpace() - p.emitToken(ast.KindAsKeyword, node.PropertyName.End(), WriteKindKeyword, node.AsNode()) + p.emitToken(ast.KindAsKeyword, node.PropertyName().End(), WriteKindKeyword, node.AsNode()) p.writeSpace() } p.emitModuleExportName(node.Name()) @@ -4242,7 +4242,7 @@ func (p *Printer) emitExternalModuleReference(node *ast.ExternalModuleReference) state := p.enterNode(node.AsNode()) p.writeKeyword("require") p.writePunctuation("(") - p.emitExpression(node.Expression, ast.OperatorPrecedenceDisallowComma) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceDisallowComma) p.writePunctuation(")") p.exitNode(node.AsNode(), state) } @@ -4253,42 +4253,42 @@ func (p *Printer) emitExternalModuleReference(node *ast.ExternalModuleReference) func (p *Printer) emitJsxElement(node *ast.JsxElement) { state := p.enterNode(node.AsNode()) - p.emitJsxOpeningElement(node.OpeningElement.AsJsxOpeningElement()) - p.emitList((*Printer).emitJsxChild, node.AsNode(), node.Children, LFJsxElementOrFragmentChildren) - p.emitJsxClosingElement(node.ClosingElement.AsJsxClosingElement()) + p.emitJsxOpeningElement(node.OpeningElement().AsJsxOpeningElement()) + p.emitList((*Printer).emitJsxChild, node.AsNode(), node.Children(), LFJsxElementOrFragmentChildren) + p.emitJsxClosingElement(node.ClosingElement().AsJsxClosingElement()) p.exitNode(node.AsNode(), state) } func (p *Printer) emitJsxSelfClosingElement(node *ast.JsxSelfClosingElement) { state := p.enterNode(node.AsNode()) p.writePunctuation("<") - p.emitJsxTagName(node.TagName) - p.emitTypeArguments(node.AsNode(), node.TypeArguments) + p.emitJsxTagName(node.TagName()) + p.emitTypeArguments(node.AsNode(), node.TypeArguments()) p.writeSpace() - p.emitJsxAttributes(node.Attributes.AsJsxAttributes()) + p.emitJsxAttributes(node.Attributes().AsJsxAttributes()) p.writePunctuation("/>") p.exitNode(node.AsNode(), state) } func (p *Printer) emitJsxFragment(node *ast.JsxFragment) { state := p.enterNode(node.AsNode()) - p.emitJsxOpeningFragment(node.OpeningFragment.AsJsxOpeningFragment()) - p.emitList((*Printer).emitJsxChild, node.AsNode(), node.Children, LFJsxElementOrFragmentChildren) - p.emitJsxClosingFragment(node.ClosingFragment.AsJsxClosingFragment()) + p.emitJsxOpeningFragment(node.OpeningFragment().AsJsxOpeningFragment()) + p.emitList((*Printer).emitJsxChild, node.AsNode(), node.Children(), LFJsxElementOrFragmentChildren) + p.emitJsxClosingFragment(node.ClosingFragment().AsJsxClosingFragment()) p.exitNode(node.AsNode(), state) } func (p *Printer) emitJsxOpeningElement(node *ast.JsxOpeningElement) { state := p.enterNode(node.AsNode()) p.writePunctuation("<") - indented := p.writeLineSeparatorsAndIndentBefore(node.TagName, node.AsNode()) - p.emitJsxTagName(node.TagName) - p.emitTypeArguments(node.AsNode(), node.TypeArguments) - if len(node.Attributes.Properties()) > 0 { + indented := p.writeLineSeparatorsAndIndentBefore(node.TagName(), node.AsNode()) + p.emitJsxTagName(node.TagName()) + p.emitTypeArguments(node.AsNode(), node.TypeArguments()) + if len(node.Attributes().Properties()) > 0 { p.writeSpace() } - p.emitJsxAttributes(node.Attributes.AsJsxAttributes()) - p.writeLineSeparatorsAfter(node.Attributes, node.AsNode()) + p.emitJsxAttributes(node.Attributes().AsJsxAttributes()) + p.writeLineSeparatorsAfter(node.Attributes(), node.AsNode()) p.decreaseIndentIf(indented) p.writePunctuation(">") p.exitNode(node.AsNode(), state) @@ -4297,7 +4297,7 @@ func (p *Printer) emitJsxOpeningElement(node *ast.JsxOpeningElement) { func (p *Printer) emitJsxClosingElement(node *ast.JsxClosingElement) { state := p.enterNode(node.AsNode()) p.writePunctuation("") p.exitNode(node.AsNode(), state) } @@ -4325,16 +4325,16 @@ func (p *Printer) emitJsxText(node *ast.JsxText) { func (p *Printer) emitJsxAttributes(node *ast.JsxAttributes) { state := p.enterNode(node.AsNode()) - p.emitList((*Printer).emitJsxAttributeLike, node.AsNode(), node.Properties, LFJsxElementAttributes) + p.emitList((*Printer).emitJsxAttributeLike, node.AsNode(), node.Properties(), LFJsxElementAttributes) p.exitNode(node.AsNode(), state) } func (p *Printer) emitJsxAttribute(node *ast.JsxAttribute) { state := p.enterNode(node.AsNode()) p.emitJsxAttributeName(node.Name()) - if node.Initializer != nil { + if node.Initializer() != nil { p.writePunctuation("=") - p.emitJsxAttributeValue(node.Initializer) + p.emitJsxAttributeValue(node.Initializer()) } p.exitNode(node.AsNode(), state) } @@ -4342,7 +4342,7 @@ func (p *Printer) emitJsxAttribute(node *ast.JsxAttribute) { func (p *Printer) emitJsxSpreadAttribute(node *ast.JsxSpreadAttribute) { state := p.enterNode(node.AsNode()) p.writePunctuation("{...") - p.emitExpression(node.Expression, ast.OperatorPrecedenceLowest) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceLowest) p.writePunctuation("}") p.exitNode(node.AsNode(), state) } @@ -4360,15 +4360,15 @@ func (p *Printer) emitJsxAttributeLike(node *ast.JsxAttributeLike) { func (p *Printer) emitJsxExpression(node *ast.JsxExpression) { state := p.enterNode(node.AsNode()) - if node.Expression != nil || !p.commentsDisabled && !ast.NodeIsSynthesized(node.AsNode()) && p.hasCommentsAtPosition(node.Pos()) { // preserve empty expressions if they contain comments! + if node.Expression() != nil || !p.commentsDisabled && !ast.NodeIsSynthesized(node.AsNode()) && p.hasCommentsAtPosition(node.Pos()) { // preserve empty expressions if they contain comments! indented := p.currentSourceFile != nil && !ast.NodeIsSynthesized(node.AsNode()) && GetLinesBetweenPositions(p.currentSourceFile, node.Pos(), node.End()) != 0 p.increaseIndentIf(indented) end := p.emitToken(ast.KindOpenBraceToken, node.Pos(), WriteKindPunctuation, node.AsNode()) - p.emitTokenNode(node.DotDotDotToken) - if node.Expression != nil { - p.emitExpression(node.Expression, ast.OperatorPrecedenceDisallowComma) + p.emitTokenNode(node.DotDotDotToken()) + if node.Expression() != nil { + p.emitExpression(node.Expression(), ast.OperatorPrecedenceDisallowComma) } - p.emitToken(ast.KindCloseBraceToken, greatestEnd(end, node.Expression, node.DotDotDotToken), WriteKindPunctuation, node.AsNode()) + p.emitToken(ast.KindCloseBraceToken, greatestEnd(end, node.Expression(), node.DotDotDotToken()), WriteKindPunctuation, node.AsNode()) p.decreaseIndentIf(indented) } p.exitNode(node.AsNode(), state) @@ -4376,7 +4376,7 @@ func (p *Printer) emitJsxExpression(node *ast.JsxExpression) { func (p *Printer) emitJsxNamespacedName(node *ast.JsxNamespacedName) { state := p.enterNode(node.AsNode()) - p.emitIdentifierName(node.Namespace.AsIdentifier()) + p.emitIdentifierName(node.Namespace().AsIdentifier()) p.writePunctuation(":") p.emitIdentifierName(node.Name().AsIdentifier()) p.exitNode(node.AsNode(), state) @@ -4447,12 +4447,12 @@ func (p *Printer) emitJsxAttributeValue(node *ast.JsxAttributeValue) { // func (p *Printer) emitCaseOrDefaultClauseStatements(node *ast.CaseOrDefaultClause, colonPos int) { - emitAsSingleStatement := len(node.Statements.Nodes) == 1 && + emitAsSingleStatement := len(node.Statements().Nodes) == 1 && // treat synthesized nodes as located on the same line for emit purposes (p.currentSourceFile == nil || ast.NodeIsSynthesized(node.AsNode()) || - ast.NodeIsSynthesized(node.Statements.Nodes[0]) || - RangeStartPositionsAreOnSameLine(node.Loc, node.Statements.Nodes[0].Loc, p.currentSourceFile)) + ast.NodeIsSynthesized(node.Statements().Nodes[0]) || + RangeStartPositionsAreOnSameLine(node.Loc, node.Statements().Nodes[0].Loc, p.currentSourceFile)) format := LFCaseOrDefaultClauseStatements if emitAsSingleStatement { @@ -4465,15 +4465,15 @@ func (p *Printer) emitCaseOrDefaultClauseStatements(node *ast.CaseOrDefaultClaus p.emitToken(ast.KindColonToken, colonPos, WriteKindPunctuation, node.AsNode()) } - p.emitList((*Printer).emitStatement, node.AsNode(), node.Statements, format) + p.emitList((*Printer).emitStatement, node.AsNode(), node.Statements(), format) } func (p *Printer) emitCaseClause(node *ast.CaseOrDefaultClause) { state := p.enterNode(node.AsNode()) p.emitToken(ast.KindCaseKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) p.writeSpace() - p.emitExpression(node.Expression, ast.OperatorPrecedenceLowest) - p.emitCaseOrDefaultClauseStatements(node, node.Expression.End()) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceLowest) + p.emitCaseOrDefaultClauseStatements(node, node.Expression().End()) p.exitNode(node.AsNode(), state) } @@ -4500,7 +4500,7 @@ func (p *Printer) emitHeritageClause(node *ast.HeritageClause) { p.writeSpace() p.emitToken(node.Token, node.Pos(), WriteKindKeyword, node.AsNode()) p.writeSpace() - p.emitList((*Printer).emitHeritageClauseElement, node.AsNode(), node.Types, LFHeritageClauseTypes) + p.emitList((*Printer).emitHeritageClauseElement, node.AsNode(), node.Types(), LFHeritageClauseTypes) p.exitNode(node.AsNode(), state) } @@ -4524,14 +4524,14 @@ func (p *Printer) emitCatchClause(node *ast.CatchClause) { openParenPos := p.emitToken(ast.KindCatchKeyword, node.Pos(), WriteKindKeyword, node.AsNode()) p.writeSpace() - if node.VariableDeclaration != nil { + if node.VariableDeclaration() != nil { p.emitToken(ast.KindOpenParenToken, openParenPos, WriteKindPunctuation, node.AsNode()) - p.emitVariableDeclaration(node.VariableDeclaration.AsVariableDeclaration()) - p.emitToken(ast.KindCloseParenToken, node.VariableDeclaration.End(), WriteKindPunctuation, node.AsNode()) + p.emitVariableDeclaration(node.VariableDeclaration().AsVariableDeclaration()) + p.emitToken(ast.KindCloseParenToken, node.VariableDeclaration().End(), WriteKindPunctuation, node.AsNode()) p.writeSpace() } - p.emitBlock(node.Block.AsBlock()) + p.emitBlock(node.Block().AsBlock()) p.exitNode(node.AsNode(), state) } @@ -4551,7 +4551,7 @@ func (p *Printer) emitPropertyAssignment(node *ast.PropertyAssignment) { // } // "comment1" is not considered to be leading comment for node.initializer // but rather a trailing comment on the previous node. - initializer := node.Initializer + initializer := node.Initializer() if p.emitContext.EmitFlags(initializer)&EFNoLeadingComments == 0 { commentRange := p.emitContext.CommentRange(initializer) p.emitTrailingComments(commentRange.Pos(), commentSeparatorAfter) @@ -4563,20 +4563,20 @@ func (p *Printer) emitPropertyAssignment(node *ast.PropertyAssignment) { func (p *Printer) emitShorthandPropertyAssignment(node *ast.ShorthandPropertyAssignment) { state := p.enterNode(node.AsNode()) p.emitPropertyName(node.Name()) - if node.ObjectAssignmentInitializer != nil { + if node.ObjectAssignmentInitializer() != nil { p.writeSpace() p.writePunctuation("=") p.writeSpace() - p.emitExpression(node.ObjectAssignmentInitializer, ast.OperatorPrecedenceDisallowComma) + p.emitExpression(node.ObjectAssignmentInitializer(), ast.OperatorPrecedenceDisallowComma) } p.exitNode(node.AsNode(), state) } func (p *Printer) emitSpreadAssignment(node *ast.SpreadAssignment) { state := p.enterNode(node.AsNode()) - if node.Expression != nil { + if node.Expression() != nil { p.emitToken(ast.KindDotDotDotToken, node.Pos(), WriteKindPunctuation, node.AsNode()) - p.emitExpression(node.Expression, ast.OperatorPrecedenceDisallowComma) + p.emitExpression(node.Expression(), ast.OperatorPrecedenceDisallowComma) } p.exitNode(node.AsNode(), state) } @@ -4588,7 +4588,7 @@ func (p *Printer) emitSpreadAssignment(node *ast.SpreadAssignment) { func (p *Printer) emitEnumMember(node *ast.EnumMember) { state := p.enterNode(node.AsNode()) p.emitPropertyName(node.Name()) - p.emitInitializer(node.Initializer, node.Name().End(), node.AsNode()) + p.emitInitializer(node.Initializer(), node.Name().End(), node.AsNode()) p.exitNode(node.AsNode(), state) } @@ -4861,7 +4861,7 @@ func (p *Printer) hasTrailingComma(parentNode *ast.Node, children *ast.NodeList) case ast.KindNamedImports, ast.KindNamedExports: originalList = originalParent.ElementList() case ast.KindImportAttributes: - originalList = originalParent.AsImportAttributes().Attributes + originalList = originalParent.AsImportAttributes().Attributes() } // if we have the original list, we can use it's result. @@ -6049,49 +6049,49 @@ func (p *Printer) generateNames(node *ast.Node) { case ast.KindLabeledStatement, ast.KindWithStatement, ast.KindDoStatement, ast.KindWhileStatement: p.generateNames(node.Statement()) case ast.KindIfStatement: - p.generateNames(node.AsIfStatement().ThenStatement) - p.generateNames(node.AsIfStatement().ElseStatement) + p.generateNames(node.AsIfStatement().ThenStatement()) + p.generateNames(node.AsIfStatement().ElseStatement()) case ast.KindForStatement, ast.KindForOfStatement, ast.KindForInStatement: p.generateNames(node.Initializer()) p.generateNames(node.Statement()) case ast.KindSwitchStatement: - p.generateNames(node.AsSwitchStatement().CaseBlock) + p.generateNames(node.AsSwitchStatement().CaseBlock()) case ast.KindCaseBlock: - p.generateAllNames(node.AsCaseBlock().Clauses) + p.generateAllNames(node.AsCaseBlock().Clauses()) case ast.KindTryStatement: - p.generateNames(node.AsTryStatement().TryBlock) - p.generateNames(node.AsTryStatement().CatchClause) - p.generateNames(node.AsTryStatement().FinallyBlock) + p.generateNames(node.AsTryStatement().TryBlock()) + p.generateNames(node.AsTryStatement().CatchClause()) + p.generateNames(node.AsTryStatement().FinallyBlock()) case ast.KindCatchClause: - p.generateNames(node.AsCatchClause().VariableDeclaration) - p.generateNames(node.AsCatchClause().Block) + p.generateNames(node.AsCatchClause().VariableDeclaration()) + p.generateNames(node.AsCatchClause().Block()) case ast.KindVariableStatement: - p.generateNames(node.AsVariableStatement().DeclarationList) + p.generateNames(node.AsVariableStatement().DeclarationList()) case ast.KindVariableDeclarationList: - p.generateAllNames(node.AsVariableDeclarationList().Declarations) + p.generateAllNames(node.AsVariableDeclarationList().Declarations()) case ast.KindVariableDeclaration, ast.KindParameter, ast.KindBindingElement, ast.KindClassDeclaration: p.generateNameIfNeeded(node.Name()) case ast.KindFunctionDeclaration: p.generateNameIfNeeded(node.Name()) if p.shouldReuseTempVariableScope(node) { - p.generateAllNames(node.AsFunctionDeclaration().Parameters) - p.generateNames(node.AsFunctionDeclaration().Body) + p.generateAllNames(node.AsFunctionDeclaration().Parameters()) + p.generateNames(node.AsFunctionDeclaration().Body()) } case ast.KindObjectBindingPattern, ast.KindArrayBindingPattern: p.generateAllNames(node.ElementList()) case ast.KindImportDeclaration, ast.KindJSImportDeclaration: - p.generateNames(node.AsImportDeclaration().ImportClause) + p.generateNames(node.AsImportDeclaration().ImportClause()) case ast.KindImportClause: p.generateNameIfNeeded(node.AsImportClause().Name()) - p.generateNames(node.AsImportClause().NamedBindings) + p.generateNames(node.AsImportClause().NamedBindings()) case ast.KindNamespaceImport, ast.KindNamespaceExport: p.generateNameIfNeeded(node.Name()) case ast.KindNamedImports: p.generateAllNames(node.ElementList()) case ast.KindImportSpecifier: n := node.AsImportSpecifier() - if n.PropertyName != nil { - p.generateNameIfNeeded(n.PropertyName) + if n.PropertyName() != nil { + p.generateNameIfNeeded(n.PropertyName()) } else { p.generateNameIfNeeded(n.Name()) } diff --git a/tsc/internal/printer/printer_test.go b/tsc/internal/printer/printer_test.go index 867ef150d491c..613c9c6671dda 100644 --- a/tsc/internal/printer/printer_test.go +++ b/tsc/internal/printer/printer_test.go @@ -2577,8 +2577,8 @@ func TestParenthesizeBinaryExpressionMixingNullishCoalescing(t *testing.T) { innerExpr, /*right: (b innerOp c)*/ ) // adjust identifiers for right side - innerExpr.AsBinaryExpression().Left = factory.NewIdentifier("b") - innerExpr.AsBinaryExpression().Right = factory.NewIdentifier("c") + innerExpr.AsBinaryExpression().SetLeft(factory.NewIdentifier("b")) + innerExpr.AsBinaryExpression().SetRight(factory.NewIdentifier("c")) } file := factory.NewSourceFile(ast.SourceFileParseOptions{FileName: "/file.ts", PathKey: "/file.ts"}, "", factory.NewNodeList( []*ast.Node{ diff --git a/tsc/internal/printer/utilities.go b/tsc/internal/printer/utilities.go index 096b4d27afe1f..3b524e0cad3c3 100644 --- a/tsc/internal/printer/utilities.go +++ b/tsc/internal/printer/utilities.go @@ -200,7 +200,7 @@ func canUseOriginalText(node *ast.LiteralLikeNode, flags getLiteralTextFlags) bo // A synthetic node has no original text, nor does a node without a parent as we would be unable to find the // containing SourceFile. We also cannot use the original text if the literal was unterminated and the caller has // requested proper termination of unterminated literals - if ast.NodeIsSynthesized(node) || node.Parent == nil || flags&getLiteralTextFlagsTerminateUnterminatedLiterals != 0 && ast.IsUnterminatedLiteral(node) { + if ast.NodeIsSynthesized(node) || node.Parent() == nil || flags&getLiteralTextFlagsTerminateUnterminatedLiterals != 0 && ast.IsUnterminatedLiteral(node) { return false } @@ -426,8 +426,8 @@ func siblingNodePositionsAreComparable(emitContext *EmitContext, previousNode *a previousNode = emitContext.MostOriginal(previousNode) nextNode = emitContext.MostOriginal(nextNode) - parent := previousNode.Parent - if parent == nil || parent != nextNode.Parent { + parent := previousNode.Parent() + if parent == nil || parent != nextNode.Parent() { return false } @@ -441,7 +441,7 @@ func siblingNodePositionsAreComparable(emitContext *EmitContext, previousNode *a } func getContainingNodeArray(node *ast.Node) *ast.NodeList { - parent := node.Parent + parent := node.Parent() if parent == nil { return nil } @@ -458,23 +458,23 @@ func getContainingNodeArray(node *ast.Node) *ast.NodeList { } case ast.KindParameter: - return node.Parent.FunctionLikeData().Parameters + return node.Parent().FunctionLikeData().Parameters() case ast.KindTemplateLiteralTypeSpan: - return node.Parent.AsTemplateLiteralTypeNode().TemplateSpans + return node.Parent().AsTemplateLiteralTypeNode().TemplateSpans() case ast.KindTemplateSpan: - return node.Parent.AsTemplateExpression().TemplateSpans + return node.Parent().AsTemplateExpression().TemplateSpans() case ast.KindDecorator: - if canHaveDecorators(node.Parent) { - if modifiers := node.Parent.Modifiers(); modifiers != nil { + if canHaveDecorators(node.Parent()) { + if modifiers := node.Parent().Modifiers(); modifiers != nil { return &modifiers.NodeList } } return nil case ast.KindHeritageClause: - if ast.IsClassLike(node.Parent) { - return node.Parent.ClassLikeData().HeritageClauses + if ast.IsClassLike(node.Parent()) { + return node.Parent().ClassLikeData().HeritageClauses() } else { - return node.Parent.AsInterfaceDeclaration().HeritageClauses + return node.Parent().AsInterfaceDeclaration().HeritageClauses() } } @@ -492,9 +492,9 @@ func getContainingNodeArray(node *ast.Node) *ast.NodeList { return parent.MemberList() } case ast.KindUnionType: - return parent.AsUnionTypeNode().Types + return parent.AsUnionTypeNode().Types() case ast.KindIntersectionType: - return parent.AsIntersectionTypeNode().Types + return parent.AsIntersectionTypeNode().Types() case ast.KindArrayLiteralExpression, ast.KindTupleType, ast.KindNamedImports, ast.KindNamedExports: return parent.ElementList() case ast.KindObjectLiteralExpression, ast.KindJsxAttributes: @@ -503,17 +503,17 @@ func getContainingNodeArray(node *ast.Node) *ast.NodeList { p := parent.AsCallExpression() switch { case ast.IsTypeNode(node): - return p.TypeArguments - case node != p.Expression: - return p.Arguments + return p.TypeArguments() + case node != p.Expression(): + return p.Arguments() } case ast.KindNewExpression: p := parent.AsNewExpression() switch { case ast.IsTypeNode(node): - return p.TypeArguments - case node != p.Expression: - return p.Arguments + return p.TypeArguments() + case node != p.Expression(): + return p.Arguments() } case ast.KindJsxElement, ast.KindJsxFragment: if ast.IsJsxChild(node) { @@ -526,7 +526,7 @@ func getContainingNodeArray(node *ast.Node) *ast.NodeList { case ast.KindBlock, ast.KindModuleBlock, ast.KindCaseClause, ast.KindDefaultClause: return parent.StatementList() case ast.KindCaseBlock: - return parent.AsCaseBlock().Clauses + return parent.AsCaseBlock().Clauses() case ast.KindClassDeclaration, ast.KindClassExpression: if ast.IsClassElement(node) { return parent.MemberList() @@ -566,11 +566,11 @@ func canHaveDecorators(node *ast.Node) bool { func originalNodesHaveSameParent(emitContext *EmitContext, nodeA *ast.Node, nodeB *ast.Node) bool { nodeA = emitContext.MostOriginal(nodeA) - if nodeA.Parent != nil { + if nodeA.Parent() != nil { // For performance, do not call `MostOriginal` for `nodeB` if `nodeA` doesn't even // have a parent node. nodeB = emitContext.MostOriginal(nodeB) - return nodeA.Parent == nodeB.Parent + return nodeA.Parent() == nodeB.Parent() } return false } @@ -625,7 +625,7 @@ func isNewExpressionWithoutArguments(node *ast.Node) bool { func isBinaryOperation(node *ast.Node, token ast.Kind) bool { node = ast.SkipPartiallyEmittedExpressions(node) return node.Kind == ast.KindBinaryExpression && - node.AsBinaryExpression().OperatorToken.Kind == token + node.AsBinaryExpression().OperatorToken().Kind == token } func mixingBinaryOperatorsRequiresParentheses(a ast.Kind, b ast.Kind) bool { diff --git a/tsc/internal/pseudochecker/lookup.go b/tsc/internal/pseudochecker/lookup.go index c2693a7ab1552..10627e73c2e6a 100644 --- a/tsc/internal/pseudochecker/lookup.go +++ b/tsc/internal/pseudochecker/lookup.go @@ -42,7 +42,7 @@ func (ch *PseudoChecker) GetTypeOfDeclaration(node *ast.Node) *PseudoType { case ast.KindBindingElement: return NewPseudoTypeNoResult(node) case ast.KindExportAssignment: - return ch.typeFromExpression(node.AsExportAssignment().Expression) + return ch.typeFromExpression(node.AsExportAssignment().Expression()) case ast.KindPropertyAccessExpression, ast.KindElementAccessExpression, ast.KindBinaryExpression: return ch.typeFromExpandoProperty(node) case ast.KindPropertyAssignment, ast.KindShorthandPropertyAssignment: @@ -109,7 +109,7 @@ func (ch *PseudoChecker) typeFromProperty(node *ast.Node) *PseudoType { } expr := ch.typeFromExpression(init) if expr != nil && (expr.Kind != PseudoTypeKindInferred || len(expr.AsPseudoTypeInferred().ErrorNodes) > 0) { - if expr.Kind != PseudoTypeKindDirect && node.AsPropertyDeclaration().PostfixToken != nil && node.AsPropertyDeclaration().PostfixToken.Kind == ast.KindQuestionToken { + if expr.Kind != PseudoTypeKindDirect && node.AsPropertyDeclaration().PostfixToken() != nil && node.AsPropertyDeclaration().PostfixToken().Kind == ast.KindQuestionToken { // type comes from the initializer expression on a property with a `?` - add `| undefined` to the type return addUndefinedIfDefinitelyRequired(expr) } @@ -122,11 +122,11 @@ func (ch *PseudoChecker) typeFromProperty(node *ast.Node) *PseudoType { } func (ch *PseudoChecker) typeFromVariable(declaration *ast.VariableDeclaration) *PseudoType { - t := declaration.Type + t := declaration.Type() if t != nil { return NewPseudoTypeDirect(t) } - init := declaration.Initializer + init := declaration.Initializer() if init != nil && declaration.Symbol != nil && (len(declaration.Symbol.Declarations) == 1 || core.CountWhere(declaration.Symbol.Declarations, ast.IsVariableDeclaration) == 1) { if !isContextuallyTyped(declaration.AsNode()) { // TODO: also should bail on expando declarations; reuse syntactic expando check used in declaration emit // TODO: Strada forces an inference fallback on `const` variables with template expression initializers, to leave space for template literal freshness in the future @@ -180,17 +180,17 @@ func (ch *PseudoChecker) getTypeAnnotationFromAccessor(node *ast.Node) *ast.Node } // !!! TODO: support ripping return type off of .FullSignature if node.Kind == ast.KindGetAccessor { - return node.AsGetAccessorDeclaration().Type + return node.AsGetAccessorDeclaration().Type() } set := node.AsSetAccessorDeclaration() - if set.Parameters == nil || len(set.Parameters.Nodes) < 1 { + if set.Parameters() == nil || len(set.Parameters().Nodes) < 1 { return nil } - p := set.Parameters.Nodes[0] + p := set.Parameters().Nodes[0] if !ast.IsParameterDeclaration(p) { return nil } - return p.AsParameterDeclaration().Type + return p.AsParameterDeclaration().Type() } func isValueSignatureDeclaration(node *ast.Node) bool { @@ -202,7 +202,7 @@ func (ch *PseudoChecker) createReturnFromSignature(fn *ast.Node) *PseudoType { if ast.IsFunctionLike(fn) { d := fn.FunctionLikeData() // !!! TODO: support ripping return type off of .FullSignature - r := d.Type + r := d.Type() if r != nil { return NewPseudoTypeDirect(r) } @@ -224,12 +224,12 @@ func (ch *PseudoChecker) typeFromSingleReturnExpression(fn *ast.Node) *PseudoTyp body := fn.Body() if ast.IsBlock(body) { ast.ForEachReturnStatement(body, func(stmt *ast.Node) bool { - if stmt.Parent != body { // Why bail on nested return statements? + if stmt.Parent() != body { // Why bail on nested return statements? candidateExpr = nil return true } if candidateExpr == nil { - candidateExpr = stmt.AsReturnStatement().Expression + candidateExpr = stmt.AsReturnStatement().Expression() } else { candidateExpr = nil return true @@ -244,9 +244,9 @@ func (ch *PseudoChecker) typeFromSingleReturnExpression(fn *ast.Node) *PseudoTyp if isContextuallyTyped(candidateExpr) { var t *ast.Node if candidateExpr.Kind == ast.KindTypeAssertionExpression { - t = candidateExpr.AsTypeAssertion().Type + t = candidateExpr.AsTypeAssertion().Type() } else if candidateExpr.Kind == ast.KindAsExpression { - t = candidateExpr.AsAsExpression().Type + t = candidateExpr.AsAsExpression().Type() } if t != nil && !ast.IsConstTypeReference(t) { return NewPseudoTypeDirect(t) @@ -265,7 +265,7 @@ func (ch *PseudoChecker) typeFromExpression(node *ast.Node) *PseudoType { return PseudoTypeUndefined case ast.KindParenthesizedExpression: // assertions transformed on reparse, just unwrap - return ch.typeFromExpression(node.AsParenthesizedExpression().Expression) + return ch.typeFromExpression(node.AsParenthesizedExpression().Expression()) case ast.KindIdentifier: // !!! TODO: in strada, this uses symbol information to ensure `node` refers to the global `undefined` symbol instead // we should probably import `resolveName` and use it here to check for the same; but we have to setup some barebones pseudoglobals for that to work! @@ -277,9 +277,9 @@ func (ch *PseudoChecker) typeFromExpression(node *ast.Node) *PseudoType { case ast.KindArrowFunction, ast.KindFunctionExpression: return ch.typeFromFunctionLikeExpression(node) case ast.KindTypeAssertionExpression: - return ch.typeFromTypeAssertion(node.AsTypeAssertion().Expression, node.AsTypeAssertion().Type) + return ch.typeFromTypeAssertion(node.AsTypeAssertion().Expression(), node.AsTypeAssertion().Type()) case ast.KindAsExpression: - return ch.typeFromTypeAssertion(node.AsAsExpression().Expression, node.AsAsExpression().Type) + return ch.typeFromTypeAssertion(node.AsAsExpression().Expression(), node.AsAsExpression().Type()) case ast.KindPrefixUnaryExpression: if ast.IsPrimitiveLiteralValue(node, true) { return ch.typeFromPrimitiveLiteralPrefix(node.AsPrefixUnaryExpression()) @@ -317,27 +317,27 @@ func (ch *PseudoChecker) typeFromObjectLiteral(node *ast.ObjectLiteralExpression return NewPseudoTypeInferredWithErrors(node.AsNode(), false, errorNodes) } // we are in a const context producing an object literal type, there are no shorthand or spread assignments - if node.Properties == nil || len(node.Properties.Nodes) == 0 { + if node.Properties() == nil || len(node.Properties().Nodes) == 0 { return NewPseudoTypeObjectLiteral(nil) } - results := make([]*PseudoObjectElement, 0, len(node.Properties.Nodes)) - for _, e := range node.Properties.Nodes { + results := make([]*PseudoObjectElement, 0, len(node.Properties().Nodes)) + for _, e := range node.Properties().Nodes { switch e.Kind { case ast.KindMethodDeclaration: - optional := e.AsMethodDeclaration().PostfixToken != nil && e.AsMethodDeclaration().PostfixToken.Kind == ast.KindQuestionToken - if e.FunctionLikeData().FullSignature != nil { + optional := e.AsMethodDeclaration().PostfixToken() != nil && e.AsMethodDeclaration().PostfixToken().Kind == ast.KindQuestionToken + if e.FunctionLikeData().FullSignature() != nil { results = append(results, NewPseudoPropertyAssignment( false, e.Name(), optional, - NewPseudoTypeDirect(e.FunctionLikeData().FullSignature), + NewPseudoTypeDirect(e.FunctionLikeData().FullSignature()), )) } else { results = append(results, NewPseudoObjectMethod( e, e.Name(), optional, - ch.cloneTypeParameters(e.AsMethodDeclaration().TypeParameters), + ch.cloneTypeParameters(e.AsMethodDeclaration().TypeParameters()), ch.cloneParameters(e.ParameterList()), ch.createReturnFromSignature(e), )) @@ -346,7 +346,7 @@ func (ch *PseudoChecker) typeFromObjectLiteral(node *ast.ObjectLiteralExpression results = append(results, NewPseudoPropertyAssignment( false, e.Name(), - e.AsPropertyAssignment().PostfixToken != nil && e.AsPropertyAssignment().PostfixToken.Kind == ast.KindQuestionToken, + e.AsPropertyAssignment().PostfixToken() != nil && e.AsPropertyAssignment().PostfixToken().Kind == ast.KindQuestionToken, ch.typeFromExpression(e.Initializer()), )) case ast.KindSetAccessor, ast.KindGetAccessor: @@ -364,8 +364,8 @@ func (ch *PseudoChecker) getAccessorMember(accessor *ast.Node, name *ast.Node) * allAccessors := ast.GetAllAccessorDeclarationsForDeclaration(accessor, accessor.Symbol().Declarations) // TODO: node preservation for late-bound accessor pairs? // TODO: handle pseudo-annotations from get accessor return positions? - if allAccessors.GetAccessor != nil && allAccessors.GetAccessor.Type != nil && - allAccessors.SetAccessor != nil && len(allAccessors.SetAccessor.Parameters.Nodes) > 0 && allAccessors.SetAccessor.Parameters.Nodes[0].AsParameterDeclaration().Type != nil { + if allAccessors.GetAccessor != nil && allAccessors.GetAccessor.Type() != nil && + allAccessors.SetAccessor != nil && len(allAccessors.SetAccessor.Parameters().Nodes) > 0 && allAccessors.SetAccessor.Parameters().Nodes[0].AsParameterDeclaration().Type() != nil { // We have possible types for both accessors, we can't know if they are the same type so we keep both accessors if ast.IsGetAccessorDeclaration(accessor) { @@ -380,7 +380,7 @@ func (ch *PseudoChecker) getAccessorMember(accessor *ast.Node, name *ast.Node) * accessor, name, false, - ch.cloneParameters(accessor.AsSetAccessorDeclaration().Parameters)[0], + ch.cloneParameters(accessor.AsSetAccessorDeclaration().Parameters())[0], ) } } @@ -404,11 +404,11 @@ func (ch *PseudoChecker) getAccessorMember(accessor *ast.Node, name *ast.Node) * // Returns nil if the object can be typed, or a slice of error nodes (shorthand/spread properties, // non-literal computed names) that prevent typing. func (ch *PseudoChecker) canGetTypeFromObjectLiteral(node *ast.ObjectLiteralExpression) []*ast.Node { - if node.Properties == nil || len(node.Properties.Nodes) == 0 { + if node.Properties() == nil || len(node.Properties().Nodes) == 0 { return nil // empty object, ok } var errorNodes []*ast.Node - for _, e := range node.Properties.Nodes { + for _, e := range node.Properties().Nodes { if e.Flags&ast.NodeFlagsThisNodeHasError != 0 { errorNodes = append(errorNodes, e) continue @@ -443,8 +443,8 @@ func (ch *PseudoChecker) typeFromArrayLiteral(node *ast.ArrayLiteralExpression) return NewPseudoTypeInferred(node.AsNode(), false) // expr in an as const cast with a contextual type has variable readonly state, bail } // we are in a const context producing a tuple type, there are no spread elements - results := make([]*PseudoType, 0, len(node.Elements.Nodes)) - for _, e := range node.Elements.Nodes { + results := make([]*PseudoType, 0, len(node.Elements().Nodes)) + for _, e := range node.Elements().Nodes { results = append(results, ch.typeFromExpression(e)) } return NewPseudoTypeTuple(results) @@ -458,7 +458,7 @@ func (ch *PseudoChecker) canGetTypeFromArrayLiteral(node *ast.ArrayLiteralExpres if !IsInConstContext(node.AsNode()) { return []*ast.Node{node.AsNode()} } - for _, e := range node.Elements.Nodes { + for _, e := range node.Elements().Nodes { if e.Kind == ast.KindSpreadElement { return []*ast.Node{e} } @@ -482,7 +482,7 @@ func isConstContextPropagatingKind(kind ast.Kind) bool { func IsInConstContext(node *ast.Node) bool { // An expression is in a const context if an ancestor is a const type maybeAssertion expression maybeAssertion := ast.FindAncestor( - node.Parent, + node.Parent(), func(n *ast.Node) bool { // stop traversing at assertions or anything not an array/object literal, since only those create or transfer const-ness return ast.IsAssertionExpression(n) || !isConstContextPropagatingKind(n.Kind) @@ -494,9 +494,9 @@ func IsInConstContext(node *ast.Node) bool { func (ch *PseudoChecker) typeFromPrimitiveLiteralPrefix(node *ast.PrefixUnaryExpression) *PseudoType { expr := node.AsNode() if node.Operator == ast.KindPlusToken { - expr = node.Operand + expr = node.Operand() } - inner := node.Operand + inner := node.Operand() if inner.Kind == ast.KindBigIntLiteral { return NewPseudoTypeMaybeConstLocation(node.AsNode(), NewPseudoTypeBigIntLiteral(expr.AsNode()), PseudoTypeBigInt) } @@ -515,12 +515,12 @@ func (ch *PseudoChecker) typeFromTypeAssertion(expression *ast.Node, typeNode *a } func (ch *PseudoChecker) typeFromFunctionLikeExpression(node *ast.Node) *PseudoType { - if node.FunctionLikeData().FullSignature != nil { - return NewPseudoTypeDirect(node.FunctionLikeData().FullSignature) + if node.FunctionLikeData().FullSignature() != nil { + return NewPseudoTypeDirect(node.FunctionLikeData().FullSignature()) } returnType := ch.createReturnFromSignature(node) - typeParameters := ch.cloneTypeParameters(node.FunctionLikeData().TypeParameters) - parameters := ch.cloneParameters(node.FunctionLikeData().Parameters) + typeParameters := ch.cloneTypeParameters(node.FunctionLikeData().TypeParameters()) + parameters := ch.cloneParameters(node.FunctionLikeData().Parameters()) return NewPseudoTypeSingleCallSignature( node, parameters, @@ -549,7 +549,7 @@ func isUndefinedPseudoType(t *PseudoType) bool { func typeNodeCouldReferToUndefined(node *ast.Node) bool { for node.Kind == ast.KindParenthesizedType { - node = node.AsParenthesizedTypeNode().Type + node = node.AsParenthesizedTypeNode().Type() } switch node.Kind { // these types require symbolic/type resolution to know if they definitely do or do not refer to `undefined`, so might (or definitely do) @@ -558,9 +558,9 @@ func typeNodeCouldReferToUndefined(node *ast.Node) bool { case ast.KindIntersectionType: // TODO: why is this not `core.Every`? strada treated unions and intersections the same, but logically every intersection member needs to contain a possible `undefined` // for the result type to contain `undefined`. Likely a bug persisting from strada. - return core.Some(node.AsIntersectionTypeNode().Types.Nodes, typeNodeCouldReferToUndefined) + return core.Some(node.AsIntersectionTypeNode().Types().Nodes, typeNodeCouldReferToUndefined) case ast.KindUnionType: - return core.Some(node.AsUnionTypeNode().Types.Nodes, typeNodeCouldReferToUndefined) + return core.Some(node.AsUnionTypeNode().Types().Nodes, typeNodeCouldReferToUndefined) case ast.KindConditionalType: // suspect - should be treated as a union of both branches instead, likely a bug persisted from strada return true case ast.KindTypeOperator: // suspect - always refers to a subset of `string | number | symbol` for `keyof` or `symbol` for `unique` @@ -596,7 +596,7 @@ func CouldAlreadyReferToUndefinedType(t *PseudoType) bool { func isOptionalInitializedOrRestParameter(node *ast.ParameterDeclarationNode) bool { p := node.AsParameterDeclaration() - if p.DotDotDotToken != nil || p.Initializer != nil || p.QuestionToken != nil { + if p.DotDotDotToken() != nil || p.Initializer() != nil || p.QuestionToken() != nil { return true } return false @@ -629,14 +629,14 @@ func addUndefinedIfDefinitelyRequired(expr *PseudoType) *PseudoType { } func (ch *PseudoChecker) typeFromParameter(node *ast.ParameterDeclaration) *PseudoType { - parent := node.Parent + parent := node.Parent() if parent.Kind == ast.KindSetAccessor { return ch.GetTypeOfAccessor(parent) } // Fast path: no initializer means we never need parameter position info. - if node.Initializer == nil { - if node.Type != nil { - return NewPseudoTypeDirect(node.Type) + if node.Initializer() == nil { + if node.Type() != nil { + return NewPseudoTypeDirect(node.Type()) } return NewPseudoTypeNoResult(node.AsNode()) } @@ -647,24 +647,24 @@ func (ch *PseudoChecker) typeFromParameter(node *ast.ParameterDeclaration) *Pseu } func (ch *PseudoChecker) typeFromParameterWorker(node *ast.ParameterDeclaration, selfIdx int, lastRequired int) *PseudoType { - parent := node.Parent + parent := node.Parent() if parent.Kind == ast.KindSetAccessor { return ch.GetTypeOfAccessor(parent) } hasRequiredAfter := selfIdx < lastRequired-1 - declaredType := node.Type + declaredType := node.Type() if declaredType != nil { result := NewPseudoTypeDirect(declaredType) // When the parameter has an initializer and strict null checks are enabled, // check if `| undefined` needs to be added because there are required parameters after this one. // This mirrors the checker's getTypeOfParameter which adds optionality for initialized parameters. - if ch.strictNullChecks && node.Initializer != nil && hasRequiredAfter { + if ch.strictNullChecks && node.Initializer() != nil && hasRequiredAfter { return addUndefinedIfDefinitelyRequired(result) } return result } - if node.Initializer != nil && ast.IsIdentifier(node.Name()) && !isContextuallyTyped(node.AsNode()) { - expr := ch.typeFromExpression(node.Initializer) + if node.Initializer() != nil && ast.IsIdentifier(node.Name()) && !isContextuallyTyped(node.AsNode()) { + expr := ch.typeFromExpression(node.Initializer()) if expr != nil && (expr.Kind == PseudoTypeKindInferred && len(expr.AsPseudoTypeInferred().ErrorNodes) == 0) { expr = NewPseudoTypeInferredWithErrors(expr.AsPseudoTypeInferred().Expression, false, []*ast.Node{node.AsNode()}) // Move error up to the parameter } @@ -695,15 +695,15 @@ func (ch *PseudoChecker) cloneParameters(nodes *ast.NodeList) []*PseudoParameter result := make([]*PseudoParameter, 0, len(nodes.Nodes)) for i, e := range nodes.Nodes { p := e.AsParameterDeclaration() - optional := p.QuestionToken != nil - if !optional && p.Initializer != nil { + optional := p.QuestionToken() != nil + if !optional && p.Initializer() != nil { // A parameter with an initializer is optional only if all subsequent // parameters are also optional/have initializers/are rest parameters. // This matches the checker's isOptionalParameter semantics. optional = i >= lastRequired-1 } result = append(result, NewPseudoParameter( - p.DotDotDotToken != nil, + p.DotDotDotToken() != nil, e.Name(), optional, ch.typeFromParameterWorker(p, i, lastRequired), @@ -713,7 +713,7 @@ func (ch *PseudoChecker) cloneParameters(nodes *ast.NodeList) []*PseudoParameter } func isContextuallyTyped(node *ast.Node) bool { - return ast.FindAncestor(node.Parent, func(n *ast.Node) bool { + return ast.FindAncestor(node.Parent(), func(n *ast.Node) bool { // Functions calls or parent type annotations (but not the return type of a function expression) may impact the inferred type and local inference is unreliable if ast.IsCallExpression(n) { return true diff --git a/tsc/internal/scanner/scanner.go b/tsc/internal/scanner/scanner.go index 785fe50a4e7df..a8eef57738d1b 100644 --- a/tsc/internal/scanner/scanner.go +++ b/tsc/internal/scanner/scanner.go @@ -2554,17 +2554,17 @@ func getErrorRangeForArrowFunction(sourceFile *ast.SourceFile, node *ast.Node) c } func findOriginatingJSDocSatisfiesTag(sourceFile *ast.SourceFile, node *ast.Node) *ast.Node { - targetType := node.AsSatisfiesExpression().Type + targetType := node.AsSatisfiesExpression().Type() if targetType.Flags&ast.NodeFlagsReparsed == 0 { return nil } - for current := node.Parent; current != nil; current = current.Parent { + for current := node.Parent(); current != nil; current = current.Parent() { if current.Flags&ast.NodeFlagsHasJSDoc == 0 { continue } var firstSatisfiesTag *ast.Node for _, jsDoc := range current.EagerJSDoc(sourceFile) { - if tags := jsDoc.AsJSDoc().Tags; tags != nil { + if tags := jsDoc.AsJSDoc().Tags(); tags != nil { for _, tag := range tags.Nodes { if !ast.IsJSDocSatisfiesTag(tag) { continue @@ -2572,7 +2572,7 @@ func findOriginatingJSDocSatisfiesTag(sourceFile *ast.SourceFile, node *ast.Node if firstSatisfiesTag == nil { firstSatisfiesTag = tag } - if typeExpr := tag.AsJSDocSatisfiesTag().TypeExpression; typeExpr != nil { + if typeExpr := tag.AsJSDocSatisfiesTag().TypeExpression(); typeExpr != nil { if t := typeExpr.Type(); t != nil && t.Loc == targetType.Loc { return tag } @@ -2627,7 +2627,7 @@ func GetErrorRangeForNode(sourceFile *ast.SourceFile, node *ast.Node) core.TextR pos := SkipTrivia(sourceFile.Text(), jsDocSatisfiesTag.TagName().Pos()) return GetRangeOfTokenAtPosition(sourceFile, pos) } - pos := SkipTrivia(sourceFile.Text(), node.AsSatisfiesExpression().Expression.End()) + pos := SkipTrivia(sourceFile.Text(), node.AsSatisfiesExpression().Expression().End()) return GetRangeOfTokenAtPosition(sourceFile, pos) case ast.KindConstructor: if node.Flags&ast.NodeFlagsReparsed != 0 { diff --git a/tsc/internal/scanner/scanner_test.go b/tsc/internal/scanner/scanner_test.go index 8f970f2af8467..7f759639a3fdb 100644 --- a/tsc/internal/scanner/scanner_test.go +++ b/tsc/internal/scanner/scanner_test.go @@ -50,12 +50,15 @@ func TestIsJSDocTypeExpressionOrChild(t *testing.T) { t.Parallel() jsDocType := &ast.Node{Kind: ast.KindTypeReference, Flags: ast.NodeFlagsJSDoc} - jsDocTypeChild := &ast.Node{Kind: ast.KindIdentifier, Flags: ast.NodeFlagsJSDoc, Parent: jsDocType} + jsDocTypeChild := &ast.Node{Kind: ast.KindIdentifier, Flags: ast.NodeFlagsJSDoc} + jsDocTypeChild.SetParent(jsDocType) reparsedType := &ast.Node{Kind: ast.KindTypeLiteral, Flags: ast.NodeFlagsReparsed} - reparsedTypeChild := &ast.Node{Kind: ast.KindIdentifier, Flags: ast.NodeFlagsReparsed, Parent: reparsedType} + reparsedTypeChild := &ast.Node{Kind: ast.KindIdentifier, Flags: ast.NodeFlagsReparsed} + reparsedTypeChild.SetParent(reparsedType) ordinaryType := &ast.Node{Kind: ast.KindTypeReference} jsDocTag := &ast.Node{Kind: ast.KindJSDocParameterTag, Flags: ast.NodeFlagsJSDoc} - jsDocTagChild := &ast.Node{Kind: ast.KindIdentifier, Flags: ast.NodeFlagsJSDoc, Parent: jsDocTag} + jsDocTagChild := &ast.Node{Kind: ast.KindIdentifier, Flags: ast.NodeFlagsJSDoc} + jsDocTagChild.SetParent(jsDocTag) tests := []struct { name string diff --git a/tsc/internal/scanner/utilities.go b/tsc/internal/scanner/utilities.go index 6a8ad06ef4ad7..01ab9b9826723 100644 --- a/tsc/internal/scanner/utilities.go +++ b/tsc/internal/scanner/utilities.go @@ -30,7 +30,7 @@ func isJSDocTypeExpressionOrChild(node *ast.Node) bool { if node.Flags&(ast.NodeFlagsJSDoc|ast.NodeFlagsReparsed) == 0 { return false } - for current := node; current != nil; current = current.Parent { + for current := node; current != nil; current = current.Parent() { if ast.IsTypeNode(current) { return true } diff --git a/tsc/internal/testrunner/compiler_runner.go b/tsc/internal/testrunner/compiler_runner.go index 2b8b4b28e6b66..85a0964e1a79c 100644 --- a/tsc/internal/testrunner/compiler_runner.go +++ b/tsc/internal/testrunner/compiler_runner.go @@ -179,6 +179,7 @@ func (r *CompilerBaselineRunner) runSingleConfigTest(t *testing.T, testName stri compilerTest.verifyModuleResolution(t, r.testSuitName) compilerTest.verifyUnionOrdering(t) compilerTest.verifyParentPointers(t) + compilerTest.verifyNodeArenas() } type compilerFileBasedTest struct { @@ -546,6 +547,15 @@ func (c *compilerTest) verifyUnionOrdering(t *testing.T) { }) } +// verifyNodeArenas checks that checking and emitting did not leave a reference in a parsed +// node that nothing keeps alive. It only does anything when the tests run with +// TSGO_ASTVERIFY=1. +func (c *compilerTest) verifyNodeArenas() { + for _, f := range c.result.Program.GetSourceFiles() { + f.VerifyArena() + } +} + func (c *compilerTest) verifyParentPointers(t *testing.T) { t.Run("source file parent pointers", func(t *testing.T) { var parent *ast.Node @@ -554,14 +564,14 @@ func (c *compilerTest) verifyParentPointers(t *testing.T) { if n == nil { return false } - assert.Assert(t, n.Parent != nil, "parent node does not exist") + assert.Assert(t, n.Parent() != nil, "parent node does not exist") elab := "" if !ast.NodeIsSynthesized(n) { elab += ast.GetSourceFileOfNode(n).Text()[n.Loc.Pos():n.Loc.End()] } else { elab += "!synthetic! no text available" } - assert.Assert(t, n.Parent == parent, "parent node does not match traversed parent: "+n.Kind.String()+": "+elab) + assert.Assert(t, n.Parent() == parent, "parent node does not match traversed parent: "+n.Kind.String()+": "+elab) oldParent := parent parent = n n.ForEachChild(verifier) diff --git a/tsc/internal/testutil/tsbaseline/type_symbol_baseline.go b/tsc/internal/testutil/tsbaseline/type_symbol_baseline.go index 343a85a74e973..06c5055a0b6d8 100644 --- a/tsc/internal/testutil/tsbaseline/type_symbol_baseline.go +++ b/tsc/internal/testutil/tsbaseline/type_symbol_baseline.go @@ -306,7 +306,7 @@ func (walker *typeWriterWalker) visitNode(node *ast.Node, isSymbolWalk bool) []* var results []*typeWriterResult for _, n := range nodes { if ast.IsExpressionNode(n) || n.Kind == ast.KindIdentifier || ast.IsDeclarationName(n) || - ast.IsQualifiedName(n) && ast.IsNameOfHeritageClauseTypeReference(n) && (isSymbolWalk || ast.IsQualifiedName(n.Parent)) { + ast.IsQualifiedName(n) && ast.IsNameOfHeritageClauseTypeReference(n) && (isSymbolWalk || ast.IsQualifiedName(n.Parent())) { result := walker.writeTypeOrSymbol(n, isSymbolWalk) if result != nil { results = append(results, result) @@ -330,8 +330,8 @@ func forEachASTNode(node *ast.Node) []*ast.Node { elem := work[len(work)-1] work = work[:len(work)-1] if elem.Flags&ast.NodeFlagsReparsed == 0 || elem.Kind == ast.KindAsExpression || elem.Kind == ast.KindSatisfiesExpression || - ((elem.Parent.Kind == ast.KindSatisfiesExpression || elem.Parent.Kind == ast.KindAsExpression) && elem == elem.Parent.Expression()) { - if elem.Flags&ast.NodeFlagsReparsed == 0 || elem.Parent.Kind == ast.KindAsExpression || elem.Parent.Kind == ast.KindSatisfiesExpression { + ((elem.Parent().Kind == ast.KindSatisfiesExpression || elem.Parent().Kind == ast.KindAsExpression) && elem == elem.Parent().Expression()) { + if elem.Flags&ast.NodeFlagsReparsed == 0 || elem.Parent().Kind == ast.KindAsExpression || elem.Parent().Kind == ast.KindSatisfiesExpression { result = append(result, elem) } elem.ForEachChild(addChild) @@ -358,8 +358,8 @@ func (walker *typeWriterWalker) writeTypeOrSymbol(node *ast.Node, isSymbolWalk b if ast.IsPartOfTypeNode(node) || (node.Kind == ast.KindAsExpression || node.Kind == ast.KindSatisfiesExpression) && node.Type().Flags&ast.NodeFlagsReparsed != 0 || ast.IsIdentifier(node) && - (ast.GetMeaningFromDeclaration(node.Parent)&ast.SemanticMeaningValue) == 0 && - !(ast.IsTypeOrJSTypeAliasDeclaration(node.Parent) && node == node.Parent.Name()) { + (ast.GetMeaningFromDeclaration(node.Parent())&ast.SemanticMeaningValue) == 0 && + !(ast.IsTypeOrJSTypeAliasDeclaration(node.Parent()) && node == node.Parent().Name()) { return nil } @@ -369,8 +369,8 @@ func (walker *typeWriterWalker) writeTypeOrSymbol(node *ast.Node, isSymbolWalk b var t *checker.Type // Workaround to ensure we output 'C' instead of 'typeof C' for base class expressions - if ast.IsExpressionWithTypeArgumentsInClassExtendsClause(node.Parent) { - t = fileChecker.GetTypeAtLocation(node.Parent) + if ast.IsExpressionWithTypeArgumentsInClassExtendsClause(node.Parent()) { + t = fileChecker.GetTypeAtLocation(node.Parent()) } if t == nil || checker.IsTypeAny(t) { t = fileChecker.GetTypeAtLocation(node) @@ -379,11 +379,11 @@ func (walker *typeWriterWalker) writeTypeOrSymbol(node *ast.Node, isSymbolWalk b // var underline string if !walker.hadErrorBaseline && checker.IsTypeAny(t) && - !ast.IsBindingElement(node.Parent) && - !ast.IsPropertyAccessOrQualifiedName(node.Parent) && + !ast.IsBindingElement(node.Parent()) && + !ast.IsPropertyAccessOrQualifiedName(node.Parent()) && !ast.IsLabelName(node) && - !ast.IsGlobalScopeAugmentation(node.Parent) && - !ast.IsMetaProperty(node.Parent) && + !ast.IsGlobalScopeAugmentation(node.Parent()) && + !ast.IsMetaProperty(node.Parent()) && !isImportStatementName(node) && !isExportStatementName(node) && !isIntrinsicJsxTag(node, walker.currentSourceFile) { @@ -391,11 +391,11 @@ func (walker *typeWriterWalker) writeTypeOrSymbol(node *ast.Node, isSymbolWalk b } else { builder := checker.NewNodeBuilder(fileChecker, ctx) typeFormatFlags := checker.TypeFormatFlagsNoTruncation | checker.TypeFormatFlagsAllowUniqueESSymbolType | checker.TypeFormatFlagsGenerateNamesForShadowedTypeParams - typeNode := builder.TypeToTypeNode(t, node.Parent, nodebuilder.Flags(typeFormatFlags&checker.TypeFormatFlagsNodeBuilderFlagsMask)|nodebuilder.FlagsIgnoreErrors, nodebuilder.InternalFlagsAllowUnresolvedNames, nil) - if ast.IsIdentifier(node) && ast.IsTypeAliasDeclaration(node.Parent) && node.Parent.Name() == node && ast.IsIdentifier(typeNode) && typeNode.Text() == node.Text() { + typeNode := builder.TypeToTypeNode(t, node.Parent(), nodebuilder.Flags(typeFormatFlags&checker.TypeFormatFlagsNodeBuilderFlagsMask)|nodebuilder.FlagsIgnoreErrors, nodebuilder.InternalFlagsAllowUnresolvedNames, nil) + if ast.IsIdentifier(node) && ast.IsTypeAliasDeclaration(node.Parent()) && node.Parent().Name() == node && ast.IsIdentifier(typeNode) && typeNode.Text() == node.Text() { // for a complex type alias `type T = ...`, showing "T : T" isn't very helpful for type tests. When the type produced is the same as // the name of the type alias, recreate the type string without reusing the alias name - typeNode = builder.TypeToTypeNode(t, node.Parent, nodebuilder.Flags((typeFormatFlags|checker.TypeFormatFlagsInTypeAlias)&checker.TypeFormatFlagsNodeBuilderFlagsMask)|nodebuilder.FlagsIgnoreErrors, nodebuilder.InternalFlagsAllowUnresolvedNames, nil) + typeNode = builder.TypeToTypeNode(t, node.Parent(), nodebuilder.Flags((typeFormatFlags|checker.TypeFormatFlagsInTypeAlias)&checker.TypeFormatFlagsNodeBuilderFlagsMask)|nodebuilder.FlagsIgnoreErrors, nodebuilder.InternalFlagsAllowUnresolvedNames, nil) } // !!! TODO: port underline printer, memoize @@ -420,7 +420,7 @@ func (walker *typeWriterWalker) writeTypeOrSymbol(node *ast.Node, isSymbolWalk b var symbolString strings.Builder symbolString.Grow(256) symbolString.WriteString("Symbol(") - symbolString.WriteString(ast.EscapeAllInternalSymbolNames(fileChecker.SymbolToStringEx(symbol, node.Parent, ast.SymbolFlagsNone, checker.SymbolFormatFlagsAllowAnyNodeKind))) + symbolString.WriteString(ast.EscapeAllInternalSymbolNames(fileChecker.SymbolToStringEx(symbol, node.Parent(), ast.SymbolFlagsNone, checker.SymbolFormatFlagsAllowAnyNodeKind))) count := 0 for _, declaration := range symbol.Declarations { if count >= 5 { @@ -455,33 +455,33 @@ func (walker *typeWriterWalker) writeTypeOrSymbol(node *ast.Node, isSymbolWalk b } func isImportStatementName(node *ast.Node) bool { - if ast.IsImportSpecifier(node.Parent) && (node == node.Parent.Name() || node == node.Parent.PropertyName()) { + if ast.IsImportSpecifier(node.Parent()) && (node == node.Parent().Name() || node == node.Parent().PropertyName()) { return true } - if ast.IsImportClause(node.Parent) && node == node.Parent.Name() { + if ast.IsImportClause(node.Parent()) && node == node.Parent().Name() { return true } - if ast.IsImportEqualsDeclaration(node.Parent) && node == node.Parent.Name() { + if ast.IsImportEqualsDeclaration(node.Parent()) && node == node.Parent().Name() { return true } return false } func isExportStatementName(node *ast.Node) bool { - if ast.IsExportAssignment(node.Parent) && node == node.Parent.Expression() { + if ast.IsExportAssignment(node.Parent()) && node == node.Parent().Expression() { return true } - if ast.IsExportSpecifier(node.Parent) && (node == node.Parent.Name() || node == node.Parent.PropertyName()) { + if ast.IsExportSpecifier(node.Parent()) && (node == node.Parent().Name() || node == node.Parent().PropertyName()) { return true } return false } func isIntrinsicJsxTag(node *ast.Node, sourceFile *ast.SourceFile) bool { - if !(ast.IsJsxOpeningElement(node.Parent) || ast.IsJsxClosingElement(node.Parent) || ast.IsJsxSelfClosingElement(node.Parent)) { + if !(ast.IsJsxOpeningElement(node.Parent()) || ast.IsJsxClosingElement(node.Parent()) || ast.IsJsxSelfClosingElement(node.Parent())) { return false } - if node.Parent.TagName() != node { + if node.Parent().TagName() != node { return false } text := scanner.GetSourceTextOfNodeFromSourceFile(sourceFile, node, false /*includeTrivia*/) diff --git a/tsc/internal/transformers/declarations/diagnostics.go b/tsc/internal/transformers/declarations/diagnostics.go index 9b2d45476a354..92be2a6d02506 100644 --- a/tsc/internal/transformers/declarations/diagnostics.go +++ b/tsc/internal/transformers/declarations/diagnostics.go @@ -96,7 +96,7 @@ func getAccessorNameVisibilityDiagnosticMessage(node *ast.Node, symbolAccessibil diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2, diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1, ) - } else if node.Parent.Kind == ast.KindClassDeclaration { + } else if node.Parent().Kind == ast.KindClassDeclaration { return selectDiagnosticBasedOnModuleName( symbolAccessibilityResult, diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named, @@ -120,7 +120,7 @@ func getMethodNameVisibilityDiagnosticMessage(node *ast.Node, symbolAccessibilit diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2, diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1, ) - } else if node.Parent.Kind == ast.KindClassDeclaration { + } else if node.Parent().Kind == ast.KindClassDeclaration { return selectDiagnosticBasedOnModuleName( symbolAccessibilityResult, diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named, @@ -144,7 +144,7 @@ func createGetSymbolAccessibilityDiagnosticForNode(node *ast.Node) GetSymbolAcce } else if ast.IsConstructSignatureDeclaration(node) || ast.IsCallSignatureDeclaration(node) || ast.IsMethodDeclaration(node) || ast.IsMethodSignatureDeclaration(node) || ast.IsFunctionDeclaration(node) || ast.IsIndexSignatureDeclaration(node) { return wrapFallbackErrorDiagnosticSelector(node, getReturnTypeVisibilityDiagnosticMessage) } else if ast.IsParameterDeclaration(node) { - if ast.IsParameterPropertyDeclaration(node, node.Parent) && ast.HasSyntacticModifier(node.Parent, ast.ModifierFlagsPrivate) { + if ast.IsParameterPropertyDeclaration(node, node.Parent()) && ast.HasSyntacticModifier(node.Parent(), ast.ModifierFlagsPrivate) { return wrapSimpleDiagnosticSelector(node, getVariableDeclarationTypeVisibilityDiagnosticMessage) } return wrapSimpleDiagnosticSelector(node, getParameterDeclarationTypeVisibilityDiagnosticMessage) @@ -155,12 +155,12 @@ func createGetSymbolAccessibilityDiagnosticForNode(node *ast.Node) GetSymbolAcce return func(symbolAccessibilityResult printer.SymbolAccessibilityResult) *SymbolAccessibilityDiagnostic { var diagnosticMessage *diagnostics.Message // Heritage clause is written by user so it can always be named - if ast.IsClassDeclaration(node.Parent.Parent) { + if ast.IsClassDeclaration(node.Parent().Parent()) { // Class or Interface implemented/extended is inaccessible - if ast.IsHeritageClause(node.Parent) && node.Parent.AsHeritageClause().Token == ast.KindImplementsKeyword { + if ast.IsHeritageClause(node.Parent()) && node.Parent().AsHeritageClause().Token == ast.KindImplementsKeyword { diagnosticMessage = diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 } else { - if node.Parent.Parent.Name() != nil { + if node.Parent().Parent().Name() != nil { diagnosticMessage = diagnostics.X_extends_clause_of_exported_class_0_has_or_is_using_private_name_1 } else { diagnosticMessage = diagnostics.X_extends_clause_of_exported_class_has_or_is_using_private_name_0 @@ -174,7 +174,7 @@ func createGetSymbolAccessibilityDiagnosticForNode(node *ast.Node) GetSymbolAcce return &SymbolAccessibilityDiagnostic{ diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: ast.GetNameOfDeclaration(node.Parent.Parent), + typeName: ast.GetNameOfDeclaration(node.Parent().Parent()), } } } else if ast.IsImportEqualsDeclaration(node) { @@ -232,7 +232,7 @@ func getVariableDeclarationTypeVisibilityDiagnosticMessage(node *ast.Node, symbo // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. } else if node.Kind == ast.KindPropertyDeclaration || node.Kind == ast.KindPropertyAccessExpression || node.Kind == ast.KindElementAccessExpression || node.Kind == ast.KindBinaryExpression || node.Kind == ast.KindPropertySignature || - (node.Kind == ast.KindParameter && ast.HasSyntacticModifier(node.Parent, ast.ModifierFlagsPrivate)) { + (node.Kind == ast.KindParameter && ast.HasSyntacticModifier(node.Parent(), ast.ModifierFlagsPrivate)) { // TODO(jfreeman): Deal with computed properties in error reporting. if ast.IsStatic(node) { return selectDiagnosticBasedOnModuleName( @@ -241,7 +241,7 @@ func getVariableDeclarationTypeVisibilityDiagnosticMessage(node *ast.Node, symbo diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2, diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1, ) - } else if node.Parent.Kind == ast.KindClassDeclaration || node.Kind == ast.KindParameter { + } else if node.Parent().Kind == ast.KindClassDeclaration || node.Kind == ast.KindParameter { return selectDiagnosticBasedOnModuleName( symbolAccessibilityResult, diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named, @@ -328,7 +328,7 @@ func getReturnTypeVisibilityDiagnosticMessage(node *ast.Node, symbolAccessibilit diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1, diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0, ) - } else if node.Parent.Kind == ast.KindClassDeclaration { + } else if node.Parent().Kind == ast.KindClassDeclaration { return selectDiagnosticBasedOnModuleName( symbolAccessibilityResult, diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named, @@ -356,7 +356,7 @@ func getReturnTypeVisibilityDiagnosticMessage(node *ast.Node, symbolAccessibilit } func getParameterDeclarationTypeVisibilityDiagnosticMessage(node *ast.Node, symbolAccessibilityResult printer.SymbolAccessibilityResult) *diagnostics.Message { - switch node.Parent.Kind { + switch node.Parent().Kind { case ast.KindConstructor: return selectDiagnosticBasedOnModuleName( symbolAccessibilityResult, @@ -390,14 +390,14 @@ func getParameterDeclarationTypeVisibilityDiagnosticMessage(node *ast.Node, symb ) case ast.KindMethodDeclaration, ast.KindMethodSignature: - if ast.IsStatic(node.Parent) { + if ast.IsStatic(node.Parent()) { return selectDiagnosticBasedOnModuleName( symbolAccessibilityResult, diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named, diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2, diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1, ) - } else if node.Parent.Parent.Kind == ast.KindClassDeclaration { + } else if node.Parent().Parent().Kind == ast.KindClassDeclaration { return selectDiagnosticBasedOnModuleName( symbolAccessibilityResult, diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named, @@ -429,13 +429,13 @@ func getParameterDeclarationTypeVisibilityDiagnosticMessage(node *ast.Node, symb ) default: - panic("Unknown parent for parameter: " + node.Parent.Kind.String()) + panic("Unknown parent for parameter: " + node.Parent().Kind.String()) } } func getTypeParameterConstraintVisibilityDiagnosticMessage(node *ast.Node, symbolAccessibilityResult printer.SymbolAccessibilityResult) *diagnostics.Message { // Type parameter constraints are named by user so we should always be able to name it - switch node.Parent.Kind { + switch node.Parent().Kind { case ast.KindClassDeclaration: return diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1 case ast.KindInterfaceDeclaration: @@ -447,9 +447,9 @@ func getTypeParameterConstraintVisibilityDiagnosticMessage(node *ast.Node, symbo case ast.KindCallSignature: return diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1 case ast.KindMethodDeclaration, ast.KindMethodSignature: - if ast.IsStatic(node.Parent) { + if ast.IsStatic(node.Parent()) { return diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1 - } else if node.Parent.Parent.Kind == ast.KindClassDeclaration { + } else if node.Parent().Parent().Kind == ast.KindClassDeclaration { return diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1 } else { return diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1 @@ -464,7 +464,7 @@ func getTypeParameterConstraintVisibilityDiagnosticMessage(node *ast.Node, symbo return diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1 default: - panic("This is unknown parent for type parameter: " + node.Parent.Kind.String()) + panic("This is unknown parent for type parameter: " + node.Parent().Kind.String()) } } @@ -661,7 +661,7 @@ func createExpressionErrorEx(node *ast.Node, diagnosticMessage *diagnostics.Mess if !ast.IsExportAssignment(parentDeclaration) && parentDeclaration.Name() != nil { targetStr = scanner.GetTextOfNode(parentDeclaration.Name()) } - parent := ast.FindAncestorOrQuit(node.Parent, isParentForIDDIagnostic) + parent := ast.FindAncestorOrQuit(node.Parent(), isParentForIDDIagnostic) if parentDeclaration == parent { if diagnosticMessage == nil { @@ -682,8 +682,8 @@ func createExpressionErrorEx(node *ast.Node, diagnosticMessage *diagnostics.Mess func createGetIsolatedDeclarationErrors(resolver printer.EmitResolver) func(node *ast.Node) *ast.Diagnostic { createParameterError := func(node *ast.Node) *ast.Diagnostic { - if ast.IsSetAccessorDeclaration(node.Parent) { - return createAccessorTypeError(node.Parent) + if ast.IsSetAccessorDeclaration(node.Parent()) { + return createAccessorTypeError(node.Parent()) } addUndefined := resolver.RequiresAddingImplicitUndefinedUnsafe(node, nil, nil) // skip checker lock - node builder will already have one if !addUndefined && node.Initializer() != nil { diff --git a/tsc/internal/transformers/declarations/tracker.go b/tsc/internal/transformers/declarations/tracker.go index 29735b2dc2b97..d1a7324786a38 100644 --- a/tsc/internal/transformers/declarations/tracker.go +++ b/tsc/internal/transformers/declarations/tracker.go @@ -58,12 +58,12 @@ func (s *SymbolTrackerImpl) ReportInaccessibleUniqueSymbolError() { } func (s *SymbolTrackerImpl) isBoundExpando(node *ast.Node) bool { - if !(ast.IsExpandoPropertyDeclaration(node) && ast.IsPropertyAccessExpression(node.AsBinaryExpression().Left)) { + if !(ast.IsExpandoPropertyDeclaration(node) && ast.IsPropertyAccessExpression(node.AsBinaryExpression().Left())) { return false } // Match transformExpandoAssignment: only an assignment rooted at an identifier (`f.x = ...`) can bind an expando // property; `this.x = ...`, `super.x = ...`, `f().x = ...` and the like have no referenced declaration. - ns := ast.GetLeftmostAccessExpression(node.AsBinaryExpression().Left) + ns := ast.GetLeftmostAccessExpression(node.AsBinaryExpression().Left()) if !ast.IsIdentifier(ns) { return false } @@ -138,7 +138,7 @@ func (s *SymbolTrackerImpl) ReportPrivateInBaseOfClassExpression(propertyName st location := s.errorLocation() if location != nil { diag := createDiagnosticForNode(location, diagnostics.Property_0_of_exported_anonymous_class_type_may_not_be_private_or_protected, propertyName) - if ast.IsVariableDeclaration(location.Parent) { + if ast.IsVariableDeclaration(location.Parent()) { related := createDiagnosticForNode(location, diagnostics.Add_a_type_annotation_to_the_variable_0, s.errorDeclarationNameWithFallback()) diag.AddRelatedInfo(related) } diff --git a/tsc/internal/transformers/declarations/transform.go b/tsc/internal/transformers/declarations/transform.go index 0daf681bfb59e..b101d46823cfb 100644 --- a/tsc/internal/transformers/declarations/transform.go +++ b/tsc/internal/transformers/declarations/transform.go @@ -121,7 +121,7 @@ func NewDeclarationTransformer(host DeclarationEmitHost, resolver printer.EmitRe if ast.IsExpandoPropertyDeclaration(p.ValueDeclaration) { errorTarget := p.ValueDeclaration if ast.IsBinaryExpression(errorTarget) { - errorTarget = errorTarget.AsBinaryExpression().Left + errorTarget = errorTarget.AsBinaryExpression().Left() } tx.state.addDiagnostic(createDiagnosticForNode(errorTarget, diagnostics.Assigning_properties_to_functions_without_declaring_them_is_not_supported_with_isolatedDeclarations_Add_an_explicit_declaration_for_the_properties_assigned_to_this_function)) } @@ -154,7 +154,7 @@ func (tx *DeclarationTransformer) isInternalDeclaration(node *ast.Node, sourceFi return false } if parseTreeNode.Kind == ast.KindParameter { - params := parseTreeNode.Parent.Parameters() + params := parseTreeNode.Parent().Parameters() paramIdx := slices.IndexFunc(params, func(p *ast.ParameterDeclarationNode) bool { return p.AsNode() == parseTreeNode }) @@ -404,7 +404,7 @@ func (tx *DeclarationTransformer) transformAndReplaceLatePaintedStatements(state tx.state.lateMarkedStatements = tx.state.lateMarkedStatements[1:] saveNeedsDeclare := tx.needsDeclare - tx.needsDeclare = next.Parent != nil && ast.IsSourceFile(next.Parent) + tx.needsDeclare = next.Parent() != nil && ast.IsSourceFile(next.Parent()) result := tx.transformTopLevelDeclaration(next) @@ -438,7 +438,7 @@ func (tx *DeclarationTransformer) transformAndReplaceLatePaintedStatements(state if needsScopeMarker(elem) { tx.needsScopeFixMarker = true } - if ast.IsSourceFile(statement.Parent) && ast.IsExternalModuleIndicator(elem) { + if ast.IsSourceFile(statement.Parent()) && ast.IsExternalModuleIndicator(elem) { tx.resultHasExternalModuleIndicator = true } } @@ -448,7 +448,7 @@ func (tx *DeclarationTransformer) transformAndReplaceLatePaintedStatements(state if needsScopeMarker(replacement) { tx.needsScopeFixMarker = true } - if ast.IsSourceFile(statement.Parent) && ast.IsExternalModuleIndicator(replacement) { + if ast.IsSourceFile(statement.Parent()) && ast.IsExternalModuleIndicator(replacement) { tx.resultHasExternalModuleIndicator = true } results = append(results, replacement) @@ -545,7 +545,7 @@ func (tx *DeclarationTransformer) getTypeReferences() (result []*ast.FileReferen func (tx *DeclarationTransformer) setupDiagnosticContext(input *ast.Node) (bool, func()) { canProduceDiagnostic := canProduceDiagnostics(input) oldWithinObjectLiteralType := tx.suppressNewDiagnosticContexts - shouldEnterSuppressNewDiagnosticsContextContext := (input.Kind == ast.KindTypeLiteral || input.Kind == ast.KindMappedType) && !(input.Parent.Kind == ast.KindTypeAliasDeclaration || input.Parent.Kind == ast.KindJSTypeAliasDeclaration) + shouldEnterSuppressNewDiagnosticsContextContext := (input.Kind == ast.KindTypeLiteral || input.Kind == ast.KindMappedType) && !(input.Parent().Kind == ast.KindTypeAliasDeclaration || input.Parent().Kind == ast.KindJSTypeAliasDeclaration) oldDiag := tx.state.getSymbolAccessibilityDiagnostic if canProduceDiagnostic && !tx.suppressNewDiagnosticContexts { @@ -577,10 +577,10 @@ func (tx *DeclarationTransformer) visitDeclarationSubtree(input *ast.Node) *ast. // Classes and object literals usually elide properties with computed names that are not of a literal type // In isolated declarations TSC needs to error on these as we don't know the type in a DTE. if !tx.resolver.IsDefinitelyReferenceToGlobalSymbolObject(input.Name().Expression()) { - if ast.IsClassDeclaration(input.Parent) || ast.IsObjectLiteralExpression(input.Parent) { + if ast.IsClassDeclaration(input.Parent()) || ast.IsObjectLiteralExpression(input.Parent()) { tx.state.addDiagnostic(createDiagnosticForNode(input, diagnostics.Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations)) return nil - } else if (ast.IsInterfaceDeclaration(input.Parent) || ast.IsTypeLiteralNode(input.Parent)) && !ast.IsEntityNameExpression(input.Name().Expression()) { + } else if (ast.IsInterfaceDeclaration(input.Parent()) || ast.IsTypeLiteralNode(input.Parent())) && !ast.IsEntityNameExpression(input.Name().Expression()) { // Type declarations just need to double-check that the input computed name is an entity name expression tx.state.addDiagnostic(createDiagnosticForNode(input, diagnostics.Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedDeclarations)) return nil @@ -601,7 +601,7 @@ func (tx *DeclarationTransformer) visitDeclarationSubtree(input *ast.Node) *ast. return nil } - if ast.IsHeritageClause(input) && (len(input.AsHeritageClause().Types.Nodes) == 0 || (len(input.AsHeritageClause().Types.Nodes) == 1 && ast.NodeIsMissing(input.AsHeritageClause().Types.Nodes[0]))) { + if ast.IsHeritageClause(input) && (len(input.AsHeritageClause().Types().Nodes) == 0 || (len(input.AsHeritageClause().Types().Nodes) == 1 && ast.NodeIsMissing(input.AsHeritageClause().Types().Nodes[0]))) { return nil } @@ -657,11 +657,11 @@ func (tx *DeclarationTransformer) visitDeclarationSubtree(input *ast.Node) *ast. case ast.KindImportType: result = tx.transformImportTypeNode(input.AsImportTypeNode()) case ast.KindTypeQuery: - tx.checkEntityNameVisibility(input.AsTypeQueryNode().ExprName, tx.enclosingDeclaration) + tx.checkEntityNameVisibility(input.AsTypeQueryNode().ExprName(), tx.enclosingDeclaration) result = tx.Visitor().VisitEachChild(input) case ast.KindQualifiedName: - if input.AsQualifiedName().Right.Kind == ast.KindPrivateIdentifier { - tx.state.addDiagnostic(createDiagnosticForNode(input, diagnostics.Declaration_emit_elides_private_members_but_0_refers_to_a_private_member_Write_an_explicit_type_here, input.AsQualifiedName().Right.Text())) + if input.AsQualifiedName().Right().Kind == ast.KindPrivateIdentifier { + tx.state.addDiagnostic(createDiagnosticForNode(input, diagnostics.Declaration_emit_elides_private_members_but_0_refers_to_a_private_member_Write_an_explicit_type_here, input.AsQualifiedName().Right().Text())) } result = tx.Visitor().VisitEachChild(input) case ast.KindTupleType: @@ -717,24 +717,24 @@ func (tx *DeclarationTransformer) checkName(node *ast.Node) { func (tx *DeclarationTransformer) transformMappedTypeNode(input *ast.MappedTypeNode) *ast.Node { // handle missing template type nodes, since the printer does not var typeNode *ast.Node - if input.Type == nil { + if input.Type() == nil { typeNode = tx.Factory().NewKeywordTypeNode(ast.KindAnyKeyword) } else { - typeNode = tx.Visitor().Visit(input.Type) + typeNode = tx.Visitor().Visit(input.Type()) } return tx.Factory().UpdateMappedTypeNode( input, - input.ReadonlyToken, - tx.Visitor().Visit(input.TypeParameter), - tx.Visitor().Visit(input.NameType), - input.QuestionToken, + input.ReadonlyToken(), + tx.Visitor().Visit(input.TypeParameter()), + tx.Visitor().Visit(input.NameType()), + input.QuestionToken(), typeNode, nil, ) } func (tx *DeclarationTransformer) transformHeritageClause(clause *ast.HeritageClause) *ast.Node { - retainedClauses := core.Filter(clause.Types.Nodes, func(t *ast.HeritageClauseElement) bool { + retainedClauses := core.Filter(clause.Types().Nodes, func(t *ast.HeritageClauseElement) bool { name := ast.GetHeritageClauseElementName(t) return ast.IsEntityName(name) || ast.IsEntityNameExpression(name) || (clause.Token == ast.KindExtendsKeyword && ast.IsExpressionWithTypeArguments(t) && t.Expression().Kind == ast.KindNullKeyword) @@ -742,7 +742,7 @@ func (tx *DeclarationTransformer) transformHeritageClause(clause *ast.HeritageCl if len(retainedClauses) == 0 { return nil // elide empty clause } - if len(retainedClauses) == len(clause.Types.Nodes) { + if len(retainedClauses) == len(clause.Types().Nodes) { return tx.Visitor().VisitEachChild(clause.AsNode()) } return tx.Factory().UpdateHeritageClause( @@ -760,12 +760,12 @@ func (tx *DeclarationTransformer) transformImportTypeNode(input *ast.ImportTypeN input, input.IsTypeOf, tx.Factory().UpdateLiteralTypeNode( - input.Argument.AsLiteralTypeNode(), - tx.rewriteModuleSpecifier(input.AsNode(), input.Argument.AsLiteralTypeNode().Literal), + input.Argument().AsLiteralTypeNode(), + tx.rewriteModuleSpecifier(input.AsNode(), input.Argument().AsLiteralTypeNode().Literal()), ), - input.Attributes, - input.Qualifier, - tx.Visitor().VisitNodes(input.TypeArguments), + input.Attributes(), + input.Qualifier(), + tx.Visitor().VisitNodes(input.TypeArguments()), ) } @@ -773,29 +773,29 @@ func (tx *DeclarationTransformer) transformConstructorTypeNode(input *ast.Constr return tx.Factory().UpdateConstructorTypeNode( input, tx.ensureModifiers(input.AsNode()), - tx.Visitor().VisitNodes(input.TypeParameters), - tx.updateParamList(input.AsNode(), input.Parameters), - tx.Visitor().Visit(input.Type), + tx.Visitor().VisitNodes(input.TypeParameters()), + tx.updateParamList(input.AsNode(), input.Parameters()), + tx.Visitor().Visit(input.Type()), ) } func (tx *DeclarationTransformer) transformFunctionTypeNode(input *ast.FunctionTypeNode) *ast.Node { return tx.Factory().UpdateFunctionTypeNode( input, - tx.Visitor().VisitNodes(input.TypeParameters), - tx.updateParamList(input.AsNode(), input.Parameters), - tx.Visitor().Visit(input.Type), + tx.Visitor().VisitNodes(input.TypeParameters()), + tx.updateParamList(input.AsNode(), input.Parameters()), + tx.Visitor().Visit(input.Type()), ) } func (tx *DeclarationTransformer) transformConditionalTypeNode(input *ast.ConditionalTypeNode) *ast.Node { - checkType := tx.Visitor().Visit(input.CheckType) - extendsType := tx.Visitor().Visit(input.ExtendsType) + checkType := tx.Visitor().Visit(input.CheckType()) + extendsType := tx.Visitor().Visit(input.ExtendsType()) oldEnclosingDecl := tx.enclosingDeclaration - tx.enclosingDeclaration = input.TrueType - trueType := tx.Visitor().Visit(input.TrueType) + tx.enclosingDeclaration = input.TrueType() + trueType := tx.Visitor().Visit(input.TrueType()) tx.enclosingDeclaration = oldEnclosingDecl - falseType := tx.Visitor().Visit(input.FalseType) + falseType := tx.Visitor().Visit(input.FalseType()) return tx.Factory().UpdateConditionalTypeNode( input, @@ -807,25 +807,25 @@ func (tx *DeclarationTransformer) transformConditionalTypeNode(input *ast.Condit } func (tx *DeclarationTransformer) transformTypeReference(input *ast.TypeReferenceNode) *ast.Node { - tx.checkEntityNameVisibility(input.TypeName, tx.enclosingDeclaration) + tx.checkEntityNameVisibility(input.TypeName(), tx.enclosingDeclaration) return tx.Visitor().VisitEachChild(input.AsNode()) } func (tx *DeclarationTransformer) transformExpressionWithTypeArguments(input *ast.ExpressionWithTypeArguments) *ast.Node { - if ast.IsEntityName(input.Expression) || ast.IsEntityNameExpression(input.Expression) { - tx.checkEntityNameVisibility(input.Expression, tx.enclosingDeclaration) + if ast.IsEntityName(input.Expression()) || ast.IsEntityNameExpression(input.Expression()) { + tx.checkEntityNameVisibility(input.Expression(), tx.enclosingDeclaration) } return tx.Visitor().VisitEachChild(input.AsNode()) } func (tx *DeclarationTransformer) transformTypeParameterDeclaration(input *ast.TypeParameterDeclaration) *ast.Node { - if isPrivateMethodTypeParameter(tx.resolver, input) && (input.DefaultType != nil || input.Constraint != nil) { + if isPrivateMethodTypeParameter(tx.resolver, input) && (input.DefaultType() != nil || input.Constraint() != nil) { return tx.Factory().UpdateTypeParameterDeclaration( input, input.Modifiers(), input.Name(), nil, - input.Expression, + input.Expression(), nil, ) } @@ -851,12 +851,12 @@ func (tx *DeclarationTransformer) transformVariableDeclaration(input *ast.Variab } func hasAnyBindingInitializers(bindingPattern *ast.BindingPattern) bool { - for _, elem := range bindingPattern.Elements.Nodes { + for _, elem := range bindingPattern.Elements().Nodes { if !ast.IsBindingElement(elem) { continue } e := elem.AsBindingElement() - if e.Initializer != nil { + if e.Initializer() != nil { return true } if e.Name() != nil && ast.IsBindingPattern(e.Name()) && hasAnyBindingInitializers(e.Name().AsBindingPattern()) { @@ -867,7 +867,7 @@ func hasAnyBindingInitializers(bindingPattern *ast.BindingPattern) bool { } func (tx *DeclarationTransformer) transformCjsRequireVariableDeclaration(input *ast.VariableDeclaration) *ast.Node { - specifier := tx.rewriteModuleSpecifier(input.AsNode(), input.Initializer.AsCallExpression().Arguments.Nodes[0]) + specifier := tx.rewriteModuleSpecifier(input.AsNode(), input.Initializer().AsCallExpression().Arguments().Nodes[0]) if ast.IsIdentifier(input.Name()) { // `const x = require("something")` -> `import x = require("something")` return tx.Factory().NewImportEqualsDeclaration(nil, false, input.Name(), tx.Factory().NewExternalModuleReference(specifier)) @@ -879,7 +879,7 @@ func (tx *DeclarationTransformer) transformCjsRequireVariableDeclaration(input * // `const {x, y: z} = require("something")` -> `import {x, y as z} from "something"` b := input.Name().AsBindingPattern() var importSpecifiers []*ast.Node - for _, elem := range b.Elements.Nodes { + for _, elem := range b.Elements().Nodes { if !ast.IsIdentifier(elem.Name()) { continue // nested destructuring, bail } @@ -900,7 +900,7 @@ func (tx *DeclarationTransformer) transformCjsRequireVariableDeclaration(input * func (tx *DeclarationTransformer) recreateBindingPattern(input *ast.BindingPattern) *ast.Node { var results []*ast.Node - for _, elem := range input.Elements.Nodes { + for _, elem := range input.Elements().Nodes { result := tx.recreateBindingElement(elem.AsBindingElement()) if result == nil { continue @@ -939,14 +939,14 @@ func (tx *DeclarationTransformer) recreateBindingElement(e *ast.BindingElement) } func (tx *DeclarationTransformer) transformIndexSignatureDeclaration(input *ast.IndexSignatureDeclaration) *ast.Node { - t := tx.Visitor().Visit(input.Type) + t := tx.Visitor().Visit(input.Type()) if t == nil { t = tx.Factory().NewKeywordTypeNode(ast.KindAnyKeyword) } return tx.Factory().UpdateIndexSignatureDeclaration( input, tx.ensureModifiers(input.AsNode()), - tx.updateParamList(input.AsNode(), input.Parameters), + tx.updateParamList(input.AsNode(), input.Parameters()), t, ) } @@ -954,8 +954,8 @@ func (tx *DeclarationTransformer) transformIndexSignatureDeclaration(input *ast. func (tx *DeclarationTransformer) transformCallSignatureDeclaration(input *ast.CallSignatureDeclaration) *ast.Node { return tx.Factory().UpdateCallSignatureDeclaration( input, - tx.ensureTypeParams(input.AsNode(), input.TypeParameters), - tx.updateParamList(input.AsNode(), input.Parameters), + tx.ensureTypeParams(input.AsNode(), input.TypeParameters()), + tx.updateParamList(input.AsNode(), input.Parameters()), tx.ensureType(input.AsNode(), false), ) } @@ -968,7 +968,7 @@ func (tx *DeclarationTransformer) transformPropertySignatureDeclaration(input *a input, tx.ensureModifiers(input.AsNode()), input.Name(), - input.PostfixToken, + input.PostfixToken(), tx.ensureType(input.AsNode(), false), tx.ensureNoInitializer(input.AsNode()), // TODO: possible strada bug (fixed here) - const property signatures never initialized ) @@ -981,7 +981,7 @@ func (tx *DeclarationTransformer) transformPropertyDeclaration(input *ast.Proper return nil } // Remove definite assignment assertion (!) from declaration files - postfixToken := input.PostfixToken + postfixToken := input.PostfixToken() if postfixToken != nil && postfixToken.Kind == ast.KindExclamationToken { postfixToken = nil } @@ -1039,10 +1039,10 @@ func (tx *DeclarationTransformer) updateAccessorParamList(input *ast.Node, isPri if ast.IsSetAccessorDeclaration(input) { var valueParam *ast.Node if !isPrivate { - if len(newParams) == 1 && len(input.AsSetAccessorDeclaration().Parameters.Nodes) >= 2 { - valueParam = tx.ensureParameter(input.AsSetAccessorDeclaration().Parameters.Nodes[1].AsParameterDeclaration()) - } else if len(newParams) == 0 && len(input.AsSetAccessorDeclaration().Parameters.Nodes) >= 1 { - valueParam = tx.ensureParameter(input.AsSetAccessorDeclaration().Parameters.Nodes[0].AsParameterDeclaration()) + if len(newParams) == 1 && len(input.AsSetAccessorDeclaration().Parameters().Nodes) >= 2 { + valueParam = tx.ensureParameter(input.AsSetAccessorDeclaration().Parameters().Nodes[1].AsParameterDeclaration()) + } else if len(newParams) == 0 && len(input.AsSetAccessorDeclaration().Parameters().Nodes) >= 1 { + valueParam = tx.ensureParameter(input.AsSetAccessorDeclaration().Parameters().Nodes[0].AsParameterDeclaration()) } } if valueParam == nil { @@ -1071,7 +1071,7 @@ func (tx *DeclarationTransformer) transformConstructorDeclaration(input *ast.Con input, tx.ensureModifiers(input.AsNode()), nil, // no type params - tx.updateParamList(input.AsNode(), input.Parameters), + tx.updateParamList(input.AsNode(), input.Parameters()), nil, // no return type nil, nil, @@ -1081,8 +1081,8 @@ func (tx *DeclarationTransformer) transformConstructorDeclaration(input *ast.Con func (tx *DeclarationTransformer) transformConstructSignatureDeclaration(input *ast.ConstructSignatureDeclaration) *ast.Node { return tx.Factory().UpdateConstructSignatureDeclaration( input, - tx.ensureTypeParams(input.AsNode(), input.TypeParameters), - tx.updateParamList(input.AsNode(), input.Parameters), + tx.ensureTypeParams(input.AsNode(), input.TypeParameters()), + tx.updateParamList(input.AsNode(), input.Parameters()), tx.ensureType(input.AsNode(), false), ) } @@ -1123,9 +1123,9 @@ func (tx *DeclarationTransformer) transformMethodSignatureDeclaration(input *ast input, tx.ensureModifiers(input.AsNode()), input.Name(), - input.PostfixToken, - tx.ensureTypeParams(input.AsNode(), input.TypeParameters), - tx.updateParamList(input.AsNode(), input.Parameters), + input.PostfixToken(), + tx.ensureTypeParams(input.AsNode(), input.TypeParameters()), + tx.updateParamList(input.AsNode(), input.Parameters()), tx.ensureType(input.AsNode(), false), ) } @@ -1142,9 +1142,9 @@ func (tx *DeclarationTransformer) transformMethodDeclaration(input *ast.MethodDe tx.ensureModifiers(input.AsNode()), nil, input.Name(), - input.PostfixToken, - tx.ensureTypeParams(input.AsNode(), input.TypeParameters), - tx.updateParamList(input.AsNode(), input.Parameters), + input.PostfixToken(), + tx.ensureTypeParams(input.AsNode(), input.TypeParameters()), + tx.updateParamList(input.AsNode(), input.Parameters()), tx.ensureType(input.AsNode(), false), nil, nil, @@ -1158,7 +1158,7 @@ func (tx *DeclarationTransformer) visitDeclarationStatements(input *ast.Node) *a } switch input.Kind { case ast.KindExportDeclaration: - if ast.IsSourceFile(input.Parent) { + if ast.IsSourceFile(input.Parent()) { tx.resultHasExternalModuleIndicator = true } tx.resultHasScopeMarker = true @@ -1167,9 +1167,9 @@ func (tx *DeclarationTransformer) visitDeclarationStatements(input *ast.Node) *a input.AsExportDeclaration(), input.Modifiers(), input.IsTypeOnly(), - input.AsExportDeclaration().ExportClause, + input.AsExportDeclaration().ExportClause(), tx.rewriteModuleSpecifier(input, input.ModuleSpecifier()), - input.AsExportDeclaration().Attributes, + input.AsExportDeclaration().Attributes(), ) case ast.KindExportAssignment: return tx.transformExportAssignment(input, input, input.Expression(), input.AsExportAssignment().IsExportEquals) @@ -1219,11 +1219,11 @@ func (tx *DeclarationTransformer) getNameOfExportedAssignedExpression(unwrapped } func (tx *DeclarationTransformer) transformExportAssignment(input *ast.Node, assignment *ast.Node, expression *ast.Node, isExportEquals bool) *ast.Node { - if ast.IsSourceFile(input.Parent) { + if ast.IsSourceFile(input.Parent()) { tx.resultHasExternalModuleIndicator = true } tx.resultHasScopeMarker = true - if ast.IsIdentifier(expression) && (ast.IsSourceFile(input.Parent) || ast.IsModuleBlock(input.Parent)) { + if ast.IsIdentifier(expression) && (ast.IsSourceFile(input.Parent()) || ast.IsModuleBlock(input.Parent())) { exportAssignment := tx.Factory().NewExportAssignment(nil, isExportEquals, nil, expression) tx.EmitContext().AssignSourceMapRange(exportAssignment, input) tx.preserveJsDoc(exportAssignment, input) @@ -1298,7 +1298,7 @@ func (tx *DeclarationTransformer) transformExportAssignment(input *ast.Node, ass func (tx *DeclarationTransformer) transformFunctionLikeToDeclaration(unwrapped *ast.Node, funcName *ast.Node, mods *ast.ModifierList, fullSignatureType *ast.Node) *ast.Node { d := unwrapped.FunctionLikeData() - sig := d.FullSignature + sig := d.FullSignature() if sig == nil { sig = fullSignatureType } @@ -1307,8 +1307,8 @@ func (tx *DeclarationTransformer) transformFunctionLikeToDeclaration(unwrapped * mods, nil, funcName, - tx.ensureTypeParams(unwrapped, d.TypeParameters), - tx.updateParamList(unwrapped, d.Parameters), + tx.ensureTypeParams(unwrapped, d.TypeParameters()), + tx.updateParamList(unwrapped, d.Parameters()), tx.ensureType(unwrapped, false), tx.Visitor().VisitNode(sig), nil, @@ -1323,7 +1323,7 @@ func (tx *DeclarationTransformer) transformFunctionLikeToDeclaration(unwrapped * } func (tx *DeclarationTransformer) transformBinaryExpressionToExportDeclaration(input *ast.Node, name *ast.Node) *ast.Node { - propertyName := input.AsBinaryExpression().Right + propertyName := input.AsBinaryExpression().Right() // track alias target so referenced declarations are included in the output tx.tracker.handleSymbolAccessibilityError(tx.resolver.IsEntityNameVisible(propertyName, tx.enclosingDeclaration)) @@ -1361,7 +1361,7 @@ func (tx *DeclarationTransformer) transformCommonJSExportWorker(input *ast.Node, tx.resultHasExternalModuleIndicator = true tx.resultHasScopeMarker = true // only transform cjs exports to shorthand at the top-level of a source file, otherwise we uniformly emit nested exports with a type annotation - if isCommonJSAliasExport(input) && ast.IsExpressionStatement(input.Parent) && ast.IsSourceFile(input.Parent.Parent) { + if isCommonJSAliasExport(input) && ast.IsExpressionStatement(input.Parent()) && ast.IsSourceFile(input.Parent().Parent()) { // export { name } // export { source as name } return tx.transformBinaryExpressionToExportDeclaration(input, name) @@ -1369,7 +1369,7 @@ func (tx *DeclarationTransformer) transformCommonJSExportWorker(input *ast.Node, // Check if the RHS is a class expression - emit as a class declaration instead of a typed variable if ast.IsBinaryExpression(input) { - if rhs := unwrapParenthesizedExpression(input.AsBinaryExpression().Right); ast.IsClassExpression(rhs) { + if rhs := unwrapParenthesizedExpression(input.AsBinaryExpression().Right()); ast.IsClassExpression(rhs) { ce := rhs.AsClassExpression() classExprName := ce.Name() hasExprName := classExprName != nil && len(classExprName.Text()) > 0 @@ -1437,9 +1437,9 @@ func (tx *DeclarationTransformer) transformCommonJSExportWorker(input *ast.Node, classDecl.AsClassDeclaration(), tx.Factory().NewModifierList(mods), classDecl.AsClassDeclaration().Name(), - classDecl.AsClassDeclaration().TypeParameters, - classDecl.AsClassDeclaration().HeritageClauses, - classDecl.AsClassDeclaration().Members, + classDecl.AsClassDeclaration().TypeParameters(), + classDecl.AsClassDeclaration().HeritageClauses(), + classDecl.AsClassDeclaration().Members(), ) return classDecl } @@ -1561,7 +1561,7 @@ func (tx *DeclarationTransformer) wrapInCJSExportNamespace(content *ast.Node) *a } func isCommonJSAliasExport(node *ast.Node) bool { - if ast.IsBinaryExpression(node) && ast.IsIdentifier(node.AsBinaryExpression().Right) { + if ast.IsBinaryExpression(node) && ast.IsIdentifier(node.AsBinaryExpression().Right()) { if symbol := node.Symbol(); symbol != nil && len(symbol.Declarations) == 1 { return true } @@ -1587,8 +1587,8 @@ func (tx *DeclarationTransformer) transformClassExpressionToDeclaration(classExp extraMembers = tx.collectThisPropertyAssignments(classExpr) } members := tx.buildClassMembers(classExpr, extraMembers...) - typeParameters := tx.ensureTypeParams(classExpr, classExpr.AsClassExpression().TypeParameters) - heritageClauses := tx.Visitor().VisitNodes(classExpr.AsClassExpression().HeritageClauses) + typeParameters := tx.ensureTypeParams(classExpr, classExpr.AsClassExpression().TypeParameters()) + heritageClauses := tx.Visitor().VisitNodes(classExpr.AsClassExpression().HeritageClauses()) return tx.Factory().NewClassDeclaration( modifiers, @@ -1620,7 +1620,7 @@ func (tx *DeclarationTransformer) preservePartialJsDoc(updated *ast.Node, origin if jsdoc == nil { return } - description := scanner.GetTextOfJSDocComment(jsdoc.AsJSDoc().Comment) + description := scanner.GetTextOfJSDocComment(jsdoc.AsJSDoc().Comment()) if description == "" { return } @@ -1795,8 +1795,8 @@ func (tx *DeclarationTransformer) transformTypeAliasDeclaration(input *ast.TypeA input, tx.ensureModifiers(input.AsNode()), input.Name(), - tx.Visitor().VisitNodes(input.TypeParameters), - tx.Visitor().Visit(input.Type), + tx.Visitor().VisitNodes(input.TypeParameters()), + tx.Visitor().Visit(input.Type()), ) } @@ -1805,9 +1805,9 @@ func (tx *DeclarationTransformer) transformInterfaceDeclaration(input *ast.Inter input, tx.ensureModifiers(input.AsNode()), input.Name(), - tx.Visitor().VisitNodes(input.TypeParameters), - tx.Visitor().VisitNodes(input.HeritageClauses), - tx.Visitor().VisitNodes(input.Members), + tx.Visitor().VisitNodes(input.TypeParameters()), + tx.Visitor().VisitNodes(input.HeritageClauses()), + tx.Visitor().VisitNodes(input.Members()), ) } @@ -1820,8 +1820,8 @@ func (tx *DeclarationTransformer) transformFunctionDeclaration(input *ast.Functi tx.ensureModifiers(input.AsNode()), nil, input.Name(), - tx.ensureTypeParams(input.AsNode(), input.TypeParameters), - tx.updateParamList(input.AsNode(), input.Parameters), + tx.ensureTypeParams(input.AsNode(), input.TypeParameters()), + tx.updateParamList(input.AsNode(), input.Parameters()), tx.ensureType(input.AsNode(), false), nil, /*fullSignature*/ nil, @@ -1835,12 +1835,12 @@ func (tx *DeclarationTransformer) transformModuleDeclaration(input *ast.ModuleDe mods := tx.ensureModifiers(input.AsNode()) saveNeedsDeclare := tx.needsDeclare tx.needsDeclare = false - inner := input.Body + inner := input.Body() keyword := input.Keyword if keyword != ast.KindGlobalKeyword && (input.Name() == nil || !ast.IsStringLiteral(input.Name())) { keyword = ast.KindNamespaceKeyword } - attributes := tx.Visitor().Visit(input.Attributes) + attributes := tx.Visitor().Visit(input.Attributes()) if inner != nil && inner.Kind == ast.KindModuleBlock { oldNeedsScopeFix := tx.needsScopeFixMarker @@ -1933,7 +1933,7 @@ func (tx *DeclarationTransformer) buildClassMembers(classNode *ast.Node, extraMe var parameterProperties []*ast.Node if ctor != nil { oldDiag := tx.state.getSymbolAccessibilityDiagnostic - for _, param := range ctor.AsConstructorDeclaration().Parameters.Nodes { + for _, param := range ctor.AsConstructorDeclaration().Parameters().Nodes { if !ast.HasSyntacticModifier(param, ast.ModifierFlagsParameterPropertyModifier) || tx.shouldStripInternal(param) { continue } @@ -1959,7 +1959,7 @@ func (tx *DeclarationTransformer) buildClassMembers(classNode *ast.Node, extraMe // When the class has at least one private identifier, create a unique constant identifier to retain the nominal typing behavior // Prevents other classes with the same public members from being used in place of the current class var privateIdentifier *ast.Node - if core.Some(classNode.ClassLikeData().Members.Nodes, func(member *ast.Node) bool { + if core.Some(classNode.ClassLikeData().Members().Nodes, func(member *ast.Node) bool { return member.Name() != nil && ast.IsPrivateIdentifier(member.Name()) }) { privateIdentifier = tx.Factory().NewPropertyDeclaration(nil, tx.Factory().NewPrivateIdentifier("#private"), nil, nil, nil) @@ -1973,14 +1973,14 @@ func (tx *DeclarationTransformer) buildClassMembers(classNode *ast.Node, extraMe tx.tracker, ) - memberNodes := make([]*ast.Node, 0, len(classNode.ClassLikeData().Members.Nodes)) + memberNodes := make([]*ast.Node, 0, len(classNode.ClassLikeData().Members().Nodes)) if privateIdentifier != nil { memberNodes = append(memberNodes, privateIdentifier) } memberNodes = append(memberNodes, lateIndexes...) memberNodes = append(memberNodes, parameterProperties...) memberNodes = append(memberNodes, extraMembers...) - visitResult := tx.Visitor().VisitNodes(classNode.ClassLikeData().Members) + visitResult := tx.Visitor().VisitNodes(classNode.ClassLikeData().Members()) if visitResult != nil && len(visitResult.Nodes) > 0 { memberNodes = append(memberNodes, visitResult.Nodes...) } @@ -1997,7 +1997,7 @@ func (tx *DeclarationTransformer) transformClassDeclaration(input *ast.ClassDecl defer tx.tracker.PopErrorFallbackNode() modifiers := tx.ensureModifiers(input.AsNode()) - typeParameters := tx.ensureTypeParams(input.AsNode(), input.TypeParameters) + typeParameters := tx.ensureTypeParams(input.AsNode(), input.TypeParameters()) // Collect this.x property assignments from constructors and static blocks in JS files var extraMembers []*ast.Node @@ -2009,8 +2009,8 @@ func (tx *DeclarationTransformer) transformClassDeclaration(input *ast.ClassDecl extendsClause := getEffectiveBaseTypeNode(input.AsNode()) - if extendsClause != nil && !ast.IsEntityNameExpression(extendsClause.AsExpressionWithTypeArguments().Expression) && extendsClause.AsExpressionWithTypeArguments().Expression.Kind != ast.KindNullKeyword { - tx.tracker.ReportInferenceFallback(extendsClause.AsExpressionWithTypeArguments().Expression) // Add an isolated declarations error on this extends clause + if extendsClause != nil && !ast.IsEntityNameExpression(extendsClause.AsExpressionWithTypeArguments().Expression()) && extendsClause.AsExpressionWithTypeArguments().Expression().Kind != ast.KindNullKeyword { + tx.tracker.ReportInferenceFallback(extendsClause.AsExpressionWithTypeArguments().Expression()) // Add an isolated declarations error on this extends clause oldId := "default" if ast.NodeIsPresent(input.Name()) && ast.IsIdentifier(input.Name()) && len(input.Name().Text()) > 0 { oldId = input.Name().Text() @@ -2039,17 +2039,17 @@ func (tx *DeclarationTransformer) transformClassDeclaration(input *ast.ClassDecl tx.Factory().NewVariableDeclarationList(tx.Factory().NewNodeList([]*ast.Node{varDecl}), ast.NodeFlagsConst), ) newHeritageClause := tx.Factory().UpdateHeritageClause( - extendsClause.Parent.AsHeritageClause(), - extendsClause.Parent.AsHeritageClause().Token, + extendsClause.Parent().AsHeritageClause(), + extendsClause.Parent().AsHeritageClause().Token, tx.Factory().NewNodeList([]*ast.Node{ tx.Factory().UpdateExpressionWithTypeArguments( extendsClause.AsExpressionWithTypeArguments(), newId, - tx.Visitor().VisitNodes(extendsClause.AsExpressionWithTypeArguments().TypeArguments), + tx.Visitor().VisitNodes(extendsClause.AsExpressionWithTypeArguments().TypeArguments()), ), }), ) - retainedHeritageClauses := tx.Visitor().VisitNodes(input.HeritageClauses) // should just be `implements` + retainedHeritageClauses := tx.Visitor().VisitNodes(input.HeritageClauses()) // should just be `implements` heritageList := []*ast.Node{ newHeritageClause, } @@ -2076,7 +2076,7 @@ func (tx *DeclarationTransformer) transformClassDeclaration(input *ast.ClassDecl modifiers, input.Name(), typeParameters, - tx.Visitor().VisitNodes(input.HeritageClauses), + tx.Visitor().VisitNodes(input.HeritageClauses()), members, ) } @@ -2085,7 +2085,7 @@ func (tx *DeclarationTransformer) visitThisPropertyAssignments(node *ast.Node) * var thisTarget *ast.Node isStatic := false thisContainer := ast.GetThisContainer(node, false, false) - thisTarget = thisContainer.Parent + thisTarget = thisContainer.Parent() if thisTarget == nil { return nil // thisContainer was source file, can't have expando-this } @@ -2109,7 +2109,7 @@ caseBlock: // problem: this prop might be overriding a prop from a base type. The checker has special bails for override compat comparisons for binary expression properties, // but what we transform to won't - so we either need to match the base type (for example, if it's a getter/setter) or emit nothing // See `checkKindsOfPropertyMemberOverrides` in the checker for what we're trying to satisfy here - if thisTarget.ClassLikeData().HeritageClauses != nil && len(thisTarget.ClassLikeData().HeritageClauses.Nodes) > 0 && !isClassExtendingNull(thisTarget) { + if thisTarget.ClassLikeData().HeritageClauses() != nil && len(thisTarget.ClassLikeData().HeritageClauses().Nodes) > 0 && !isClassExtendingNull(thisTarget) { // there is a base type any assignments might be "from" tx.tracker.ReportInferenceFallback(thisTarget) // Add an isolated declarations error on this class - we can't know how to transform this prop into an assignment without referring to type information if tx.resolver.IsThisPropertyAssignmentDeclarationRedundant(node) { @@ -2142,8 +2142,8 @@ caseBlock: tx.ensureType(node, false), nil, ) - if ast.IsExpressionStatement(node.Parent) { - tx.preserveJsDoc(prop, node.Parent) + if ast.IsExpressionStatement(node.Parent()) { + tx.preserveJsDoc(prop, node.Parent()) } tx.thisPropertyAssignmentsCollected = append(tx.thisPropertyAssignmentsCollected, prop) } @@ -2158,18 +2158,18 @@ func isClassExtendingNull(node *ast.Node) bool { if extendsClause == nil { return false } - types := extendsClause.AsHeritageClause().Types + types := extendsClause.AsHeritageClause().Types() if types == nil || len(types.Nodes) != 1 { return false } - expr := types.Nodes[0].AsExpressionWithTypeArguments().Expression + expr := types.Nodes[0].AsExpressionWithTypeArguments().Expression() return expr != nil && expr.Kind == ast.KindNullKeyword } // collectThisPropertyAssignments finds `this.x = expr` assignments in constructors, methods, and static blocks // of JS classes and synthesizes PropertyDeclaration nodes for each unique property name. func (tx *DeclarationTransformer) collectThisPropertyAssignments(classNode *ast.Node) []*ast.Node { - members := classNode.ClassLikeData().Members + members := classNode.ClassLikeData().Members() seen := collections.Set[thisPropertyAssignmentKey]{} // Pre-populate seen with existing direct member nodes to avoid duplicates for _, member := range members.Nodes { @@ -2193,7 +2193,7 @@ func (tx *DeclarationTransformer) collectThisPropertyAssignments(classNode *ast. func (tx *DeclarationTransformer) walkBindingPattern(pattern *ast.BindingPattern, param *ast.Node) []*ast.Node { var elems []*ast.Node - for _, elem := range pattern.Elements.Nodes { + for _, elem := range pattern.Elements().Nodes { if ast.IsOmittedExpression(elem) { continue } @@ -2214,7 +2214,7 @@ func (tx *DeclarationTransformer) walkBindingPattern(pattern *ast.BindingPattern func (tx *DeclarationTransformer) transformVariableStatement(input *ast.VariableStatement) *ast.Node { visible := false - for _, decl := range input.DeclarationList.AsVariableDeclarationList().Declarations.Nodes { + for _, decl := range input.DeclarationList().AsVariableDeclarationList().Declarations().Nodes { visible = getBindingNameVisible(tx.resolver, decl) if visible { break @@ -2224,7 +2224,7 @@ func (tx *DeclarationTransformer) transformVariableStatement(input *ast.Variable return nil } - inputNodes := input.DeclarationList.AsVariableDeclarationList().Declarations.Nodes + inputNodes := input.DeclarationList().AsVariableDeclarationList().Declarations().Nodes var extraImports []*ast.Node if tx.state.currentSourceFile.CommonJSModuleIndicator != nil { var normalDeclarations []*ast.Node @@ -2252,13 +2252,13 @@ func (tx *DeclarationTransformer) transformVariableStatement(input *ast.Variable modifiers := tx.ensureModifiers(input.AsNode()) var declList *ast.Node - if ast.IsVarUsing(input.DeclarationList) || ast.IsVarAwaitUsing(input.DeclarationList) { + if ast.IsVarUsing(input.DeclarationList()) || ast.IsVarAwaitUsing(input.DeclarationList()) { declList = tx.Factory().NewVariableDeclarationList(nodeList, ast.NodeFlagsConst) - tx.EmitContext().SetOriginal(declList, input.DeclarationList) - tx.EmitContext().SetCommentRange(declList, input.DeclarationList.Loc) - declList.Loc = input.DeclarationList.Loc + tx.EmitContext().SetOriginal(declList, input.DeclarationList()) + tx.EmitContext().SetCommentRange(declList, input.DeclarationList().Loc) + declList.Loc = input.DeclarationList().Loc } else { - declList = tx.Factory().UpdateVariableDeclarationList(input.DeclarationList.AsVariableDeclarationList(), nodeList, input.DeclarationList.Flags) + declList = tx.Factory().UpdateVariableDeclarationList(input.DeclarationList().AsVariableDeclarationList(), nodeList, input.DeclarationList().Flags) } res := tx.Factory().UpdateVariableStatement(input, modifiers, declList) if len(extraImports) > 0 { @@ -2272,7 +2272,7 @@ func (tx *DeclarationTransformer) transformEnumDeclaration(input *ast.EnumDeclar input, tx.ensureModifiers(input.AsNode()), input.Name(), - tx.Factory().NewNodeList(core.MapNonNil(input.Members.Nodes, func(m *ast.Node) *ast.Node { + tx.Factory().NewNodeList(core.MapNonNil(input.Members().Nodes, func(m *ast.Node) *ast.Node { if tx.shouldStripInternal(m) { return nil } @@ -2344,7 +2344,7 @@ func (tx *DeclarationTransformer) ensureModifierFlags(node *ast.Node) ast.Modifi if tx.needsDeclare && !isAlwaysType(node) { additions = ast.ModifierFlagsAmbient } - parentIsFile := node.Parent.Kind == ast.KindSourceFile + parentIsFile := node.Parent().Kind == ast.KindSourceFile if !parentIsFile { mask ^= ast.ModifierFlagsAmbient additions = ast.ModifierFlagsNone @@ -2373,12 +2373,10 @@ func (tx *DeclarationTransformer) ensureTypeParams(node *ast.Node, params *ast.T } } - if data := node.FunctionLikeData(); data != nil && data.FullSignature != nil { + if data := node.FunctionLikeData(); data != nil && data.FullSignature() != nil { if nodes := tx.resolver.CreateTypeParametersOfSignatureDeclaration(node, tx.enclosingDeclaration, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, tx.tracker); nodes != nil { - typeParameters = &ast.TypeParameterList{ - Loc: node.Loc, - Nodes: nodes, - } + typeParameters = tx.Factory().NewNodeList(nodes) + typeParameters.Loc = node.Loc } } @@ -2407,8 +2405,8 @@ func (tx *DeclarationTransformer) ensureParameter(p *ast.ParameterDeclaration) * } var questionToken *ast.TokenNode if tx.resolver.IsOptionalParameter(p.AsNode()) { - if p.QuestionToken != nil { - questionToken = p.QuestionToken + if p.QuestionToken() != nil { + questionToken = p.QuestionToken() } else { questionToken = tx.Factory().NewToken(ast.KindQuestionToken) } @@ -2416,7 +2414,7 @@ func (tx *DeclarationTransformer) ensureParameter(p *ast.ParameterDeclaration) * result := tx.Factory().UpdateParameterDeclaration( p, nil, - p.DotDotDotToken, + p.DotDotDotToken(), tx.bindingNameVisitor.VisitNode(p.Name()), questionToken, tx.ensureType(p.AsNode(), true), @@ -2447,7 +2445,7 @@ func (tx *DeclarationTransformer) visitBindingName(node *ast.Node) *ast.Node { if node.PropertyName() != nil && ast.IsComputedPropertyName(node.PropertyName()) && ast.IsEntityNameExpression(node.PropertyName().Expression()) { tx.checkEntityNameVisibility(node.PropertyName().Expression(), tx.enclosingDeclaration) } - return tx.Factory().UpdateBindingElement(node.AsBindingElement(), node.AsBindingElement().DotDotDotToken, node.PropertyName(), tx.bindingNameVisitor.VisitNode(node.Name()), nil /*initializer*/) + return tx.Factory().UpdateBindingElement(node.AsBindingElement(), node.AsBindingElement().DotDotDotToken(), node.PropertyName(), tx.bindingNameVisitor.VisitNode(node.Name()), nil /*initializer*/) default: return node } @@ -2457,7 +2455,7 @@ func (tx *DeclarationTransformer) transformImportEqualsDeclaration(decl *ast.Imp if !tx.resolver.IsDeclarationVisible(decl.AsNode()) { return nil } - if decl.ModuleReference.Kind == ast.KindExternalModuleReference { + if decl.ModuleReference().Kind == ast.KindExternalModuleReference { // Rewrite external module names if necessary specifier := ast.GetExternalModuleImportEqualsDeclarationExpression(decl.AsNode()) return tx.Factory().UpdateImportEqualsDeclaration( @@ -2465,38 +2463,38 @@ func (tx *DeclarationTransformer) transformImportEqualsDeclaration(decl *ast.Imp decl.Modifiers(), decl.IsTypeOnly, decl.Name(), - tx.Factory().UpdateExternalModuleReference(decl.ModuleReference.AsExternalModuleReference(), tx.rewriteModuleSpecifier(decl.AsNode(), specifier)), + tx.Factory().UpdateExternalModuleReference(decl.ModuleReference().AsExternalModuleReference(), tx.rewriteModuleSpecifier(decl.AsNode(), specifier)), ) } else { oldDiag := tx.state.getSymbolAccessibilityDiagnostic tx.state.getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(decl.AsNode()) - tx.checkEntityNameVisibility(decl.ModuleReference, tx.enclosingDeclaration) + tx.checkEntityNameVisibility(decl.ModuleReference(), tx.enclosingDeclaration) tx.state.getSymbolAccessibilityDiagnostic = oldDiag return decl.AsNode() } } func (tx *DeclarationTransformer) transformImportDeclaration(decl *ast.ImportDeclaration) *ast.Node { - if decl.ImportClause == nil { + if decl.ImportClause() == nil { // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc) return tx.Factory().UpdateImportDeclaration( decl, decl.Modifiers(), - decl.ImportClause, - tx.rewriteModuleSpecifier(decl.AsNode(), decl.ModuleSpecifier), - decl.Attributes, + decl.ImportClause(), + tx.rewriteModuleSpecifier(decl.AsNode(), decl.ModuleSpecifier()), + decl.Attributes(), ) } - phaseModifier := decl.ImportClause.AsImportClause().PhaseModifier + phaseModifier := decl.ImportClause().AsImportClause().PhaseModifier if phaseModifier == ast.KindDeferKeyword { phaseModifier = ast.KindUnknown } // The `importClause` visibility corresponds to the default's visibility. var visibleDefaultBinding *ast.Node - if decl.ImportClause != nil && decl.ImportClause.Name() != nil && tx.resolver.IsDeclarationVisible(decl.ImportClause) { - visibleDefaultBinding = decl.ImportClause.Name() + if decl.ImportClause() != nil && decl.ImportClause().Name() != nil && tx.resolver.IsDeclarationVisible(decl.ImportClause()) { + visibleDefaultBinding = decl.ImportClause().Name() } - if decl.ImportClause.AsImportClause().NamedBindings == nil { + if decl.ImportClause().AsImportClause().NamedBindings() == nil { // No named bindings (either namespace or list), meaning the import is just default or should be elided if visibleDefaultBinding == nil { return nil @@ -2505,20 +2503,20 @@ func (tx *DeclarationTransformer) transformImportDeclaration(decl *ast.ImportDec decl, decl.Modifiers(), tx.Factory().UpdateImportClause( - decl.ImportClause.AsImportClause(), + decl.ImportClause().AsImportClause(), phaseModifier, visibleDefaultBinding, /*namedBindings*/ nil, ), - tx.rewriteModuleSpecifier(decl.AsNode(), decl.ModuleSpecifier), - decl.Attributes, + tx.rewriteModuleSpecifier(decl.AsNode(), decl.ModuleSpecifier()), + decl.Attributes(), ) } - if decl.ImportClause.AsImportClause().NamedBindings.Kind == ast.KindNamespaceImport { + if decl.ImportClause().AsImportClause().NamedBindings().Kind == ast.KindNamespaceImport { // Namespace import (optionally with visible default) var namedBindings *ast.Node - if tx.resolver.IsDeclarationVisible(decl.ImportClause.AsImportClause().NamedBindings) { - namedBindings = decl.ImportClause.AsImportClause().NamedBindings + if tx.resolver.IsDeclarationVisible(decl.ImportClause().AsImportClause().NamedBindings()) { + namedBindings = decl.ImportClause().AsImportClause().NamedBindings() } if visibleDefaultBinding == nil && namedBindings == nil { return nil @@ -2527,18 +2525,18 @@ func (tx *DeclarationTransformer) transformImportDeclaration(decl *ast.ImportDec decl, decl.Modifiers(), tx.Factory().UpdateImportClause( - decl.ImportClause.AsImportClause(), + decl.ImportClause().AsImportClause(), phaseModifier, visibleDefaultBinding, namedBindings, ), - tx.rewriteModuleSpecifier(decl.AsNode(), decl.ModuleSpecifier), - decl.Attributes, + tx.rewriteModuleSpecifier(decl.AsNode(), decl.ModuleSpecifier()), + decl.Attributes(), ) } // Named imports (optionally with visible default) bindingList := core.Filter( - decl.ImportClause.AsImportClause().NamedBindings.Elements(), + decl.ImportClause().AsImportClause().NamedBindings().Elements(), func(b *ast.Node) bool { return tx.resolver.IsDeclarationVisible(b) }, @@ -2547,7 +2545,7 @@ func (tx *DeclarationTransformer) transformImportDeclaration(decl *ast.ImportDec var namedImports *ast.Node if len(bindingList) > 0 { namedImports = tx.Factory().UpdateNamedImports( - decl.ImportClause.AsImportClause().NamedBindings.AsNamedImports(), + decl.ImportClause().AsImportClause().NamedBindings().AsNamedImports(), tx.Factory().NewNodeList(bindingList), ) } @@ -2555,13 +2553,13 @@ func (tx *DeclarationTransformer) transformImportDeclaration(decl *ast.ImportDec decl, decl.Modifiers(), tx.Factory().UpdateImportClause( - decl.ImportClause.AsImportClause(), + decl.ImportClause().AsImportClause(), phaseModifier, visibleDefaultBinding, namedImports, ), - tx.rewriteModuleSpecifier(decl.AsNode(), decl.ModuleSpecifier), - decl.Attributes, + tx.rewriteModuleSpecifier(decl.AsNode(), decl.ModuleSpecifier()), + decl.Attributes(), ) } // Augmentation of export depends on import @@ -2573,8 +2571,8 @@ func (tx *DeclarationTransformer) transformImportDeclaration(decl *ast.ImportDec decl, decl.Modifiers(), /*importClause*/ nil, - tx.rewriteModuleSpecifier(decl.AsNode(), decl.ModuleSpecifier), - decl.Attributes, + tx.rewriteModuleSpecifier(decl.AsNode(), decl.ModuleSpecifier()), + decl.Attributes(), ) } // Nothing visible @@ -2582,7 +2580,7 @@ func (tx *DeclarationTransformer) transformImportDeclaration(decl *ast.ImportDec } func (tx *DeclarationTransformer) transformJSDocTypeExpression(input *ast.JSDocTypeExpression) *ast.Node { - return tx.Visitor().Visit(input.Type) + return tx.Visitor().Visit(input.Type()) } func (tx *DeclarationTransformer) transformJSDocTypeLiteral(input *ast.JSDocTypeLiteral) *ast.Node { @@ -2595,9 +2593,9 @@ func (tx *DeclarationTransformer) transformJSDocTypeLiteral(input *ast.JSDocType func (tx *DeclarationTransformer) transformJSDocPropertyTag(input *ast.JSDocParameterOrPropertyTag) *ast.Node { replacement := tx.Factory().NewPropertySignatureDeclaration( nil, - tx.Visitor().Visit(input.TagName), + tx.Visitor().Visit(input.TagName()), nil, - tx.Visitor().Visit(input.TypeExpression), + tx.Visitor().Visit(input.TypeExpression()), nil, ) tx.EmitContext().SetOriginal(replacement, input.AsNode()) @@ -2612,7 +2610,7 @@ func (tx *DeclarationTransformer) transformJSDocAllType(input *ast.JSDocAllType) func (tx *DeclarationTransformer) transformJSDocNullableType(input *ast.JSDocNullableType) *ast.Node { replacement := tx.Factory().NewUnionTypeNode(tx.Factory().NewNodeList([]*ast.Node{ - tx.Visitor().Visit(input.Type), + tx.Visitor().Visit(input.Type()), tx.Factory().NewLiteralTypeNode(tx.Factory().NewKeywordExpression(ast.KindNullKeyword)), })) tx.EmitContext().SetOriginal(replacement, input.AsNode()) @@ -2620,18 +2618,18 @@ func (tx *DeclarationTransformer) transformJSDocNullableType(input *ast.JSDocNul } func (tx *DeclarationTransformer) transformJSDocNonNullableType(input *ast.JSDocNonNullableType) *ast.Node { - return tx.Visitor().Visit(input.Type) + return tx.Visitor().Visit(input.Type()) } func (tx *DeclarationTransformer) transformJSDocVariadicType(input *ast.JSDocVariadicType) *ast.Node { - replacement := tx.Factory().NewArrayTypeNode(tx.Visitor().Visit(input.Type)) + replacement := tx.Factory().NewArrayTypeNode(tx.Visitor().Visit(input.Type())) tx.EmitContext().SetOriginal(replacement, input.AsNode()) return replacement } func (tx *DeclarationTransformer) transformJSDocOptionalType(input *ast.JSDocOptionalType) *ast.Node { replacement := tx.Factory().NewUnionTypeNode(tx.Factory().NewNodeList([]*ast.Node{ - tx.Visitor().Visit(input.Type), + tx.Visitor().Visit(input.Type()), tx.Factory().NewKeywordTypeNode(ast.KindUndefinedKeyword), })) tx.EmitContext().SetOriginal(replacement, input.AsNode()) @@ -2649,7 +2647,7 @@ func (tx *DeclarationTransformer) getNameExpressionPreferringIdentifier(nameExpr // keep keywords as strings, except `default`, which has special reformulations in the transformer if kwKind == ast.KindUnknown || kwKind == ast.KindDefaultKeyword { // fake this into a parse tree node so the reference resolver resolves the node via `resolveName` - result.Parent = nameExpr.Parent + result.SetParent(nameExpr.Parent()) result.Flags &^= ast.NodeFlagsSynthesized // intentionally leave Loc unset so the string isn't used as the text source of the identifier return result @@ -2684,7 +2682,7 @@ func (tx *DeclarationTransformer) visitCJSExportAssignments(expression *ast.Node switch ast.GetAssignmentDeclarationKind(expression) { case ast.JSDeclarationKindModuleExports: if tx.state.currentSourceFile.CommonJSModuleIndicator != nil { - result := tx.transformExportAssignment(expression.Parent, expression, expression.AsBinaryExpression().Right, true /*isExportEquals*/) + result := tx.transformExportAssignment(expression.Parent(), expression, expression.AsBinaryExpression().Right(), true /*isExportEquals*/) if result != nil { tx.cjsExportAssignment = result tx.resultHasScopeMarker = true @@ -2706,7 +2704,7 @@ func (tx *DeclarationTransformer) visitNestedExpression(expression *ast.Node) *a tx.transformExpandoAssignment(expression.AsBinaryExpression()) case ast.JSDeclarationKindExportsProperty: if tx.state.currentSourceFile.CommonJSModuleIndicator != nil { - result := tx.transformCommonJSExport(expression, tx.getNameExpressionPreferringIdentifier(ast.GetElementOrPropertyAccessName(expression.AsBinaryExpression().Left))) + result := tx.transformCommonJSExport(expression, tx.getNameExpressionPreferringIdentifier(ast.GetElementOrPropertyAccessName(expression.AsBinaryExpression().Left()))) if result != nil { tx.cjsExportMembers = append(tx.cjsExportMembers, result) } @@ -2725,7 +2723,7 @@ func (tx *DeclarationTransformer) visitNestedExpression(expression *ast.Node) *a } func (tx *DeclarationTransformer) transformExpandoAssignment(node *ast.BinaryExpression) { - left := node.Left + left := node.Left() symbol := node.Symbol if symbol == nil || symbol.Flags&ast.SymbolFlagsAssignment == 0 { @@ -2750,7 +2748,7 @@ func (tx *DeclarationTransformer) transformExpandoAssignment(node *ast.BinaryExp return } - if ast.IsFunctionDeclaration(declaration) && declaration.FunctionLikeData().FullSignature != nil { + if ast.IsFunctionDeclaration(declaration) && declaration.FunctionLikeData().FullSignature() != nil { return } @@ -2801,7 +2799,7 @@ func (tx *DeclarationTransformer) transformExpandoAssignment(node *ast.BinaryExp preexistingExpandoHasExport := core.Some(tx.expandoMembers[hostId], ast.IsExportDeclaration) - if ast.IsIdentifier(node.Right) { + if ast.IsIdentifier(node.Right()) { if !preexistingExpandoHasExport { tx.addExportModifierToExpandoMembers(hostId) } @@ -2818,12 +2816,9 @@ func (tx *DeclarationTransformer) transformExpandoAssignment(node *ast.BinaryExp } synthesizedNamespace := tx.Factory().NewModuleDeclaration(nil /*modifiers*/, ast.KindNamespaceKeyword, name, nil, tx.Factory().NewModuleBlock(tx.Factory().NewNodeList([]*ast.Node{}))) - synthesizedNamespace.Parent = tx.enclosingDeclaration - declarationData := synthesizedNamespace.DeclarationData() - declarationData.Symbol = host - containerData := synthesizedNamespace.LocalsContainerData() - containerData.Locals = make(ast.SymbolTable, 0) - containerData.Locals[localName.Text()] = symbol + synthesizedNamespace.SetParent(tx.enclosingDeclaration) + ast.SetSymbol(synthesizedNamespace, host) + ast.SetLocals(synthesizedNamespace, ast.SymbolTable{localName.Text(): symbol}) oldEnclosing := tx.enclosingDeclaration tx.enclosingDeclaration = synthesizedNamespace @@ -2869,13 +2864,13 @@ func (tx *DeclarationTransformer) addExportModifierToExpandoMembers(hostId ast.N } func (tx *DeclarationTransformer) getExpandoHostId(declaration *ast.Declaration) ast.NodeId { - root := core.IfElse(ast.IsVariableDeclaration(declaration), declaration.Parent.Parent, declaration) + root := core.IfElse(ast.IsVariableDeclaration(declaration), declaration.Parent().Parent(), declaration) id := ast.GetNodeId(tx.EmitContext().MostOriginal(root)) return id } func (tx *DeclarationTransformer) transformExpandoHost(name *ast.Node, declaration *ast.Declaration) { - root := core.IfElse(ast.IsVariableDeclaration(declaration), declaration.Parent.Parent, declaration) + root := core.IfElse(ast.IsVariableDeclaration(declaration), declaration.Parent().Parent(), declaration) id := tx.getExpandoHostId(declaration) if _, ok := tx.expandoHosts[id]; ok { @@ -2917,7 +2912,7 @@ func (tx *DeclarationTransformer) transformExpandoHost(name *ast.Node, declarati tx.state.reportExpandoFunctionErrors(declaration) if defaultExport { - if ast.IsSourceFile(declaration.Parent) { + if ast.IsSourceFile(declaration.Parent()) { tx.resultHasExternalModuleIndicator = true } tx.resultHasScopeMarker = true @@ -2984,13 +2979,13 @@ func extractExpandoHostParams(node *ast.Node) (typeParameters *ast.TypeParameter switch node.Kind { case ast.KindFunctionExpression: fn := node.AsFunctionExpression() - return fn.TypeParameters, fn.Parameters, fn.AsteriskToken + return fn.TypeParameters(), fn.Parameters(), fn.AsteriskToken() case ast.KindArrowFunction: fn := node.AsArrowFunction() - return fn.TypeParameters, fn.Parameters, fn.AsteriskToken + return fn.TypeParameters(), fn.Parameters(), fn.AsteriskToken() default: fn := node.AsFunctionDeclaration() - return fn.TypeParameters, fn.Parameters, fn.AsteriskToken + return fn.TypeParameters(), fn.Parameters(), fn.AsteriskToken() } } diff --git a/tsc/internal/transformers/declarations/util.go b/tsc/internal/transformers/declarations/util.go index 422a62134808f..8ef37287ca946 100644 --- a/tsc/internal/transformers/declarations/util.go +++ b/tsc/internal/transformers/declarations/util.go @@ -147,17 +147,17 @@ func unwrapParenthesizedExpression(o *ast.Node) *ast.Node { } func isPrivateMethodTypeParameter(resolver printer.EmitResolver, node *ast.TypeParameterDeclaration) bool { - return node.AsNode().Parent.Kind == ast.KindMethodDeclaration && resolver.GetEffectiveDeclarationFlags(node.AsNode().Parent, ast.ModifierFlagsPrivate) != 0 + return node.AsNode().Parent().Kind == ast.KindMethodDeclaration && resolver.GetEffectiveDeclarationFlags(node.AsNode().Parent(), ast.ModifierFlagsPrivate) != 0 } // Returns true if expando properties should be emitted for this function. // Properties are emitted if any overload in the symbol has a body (implementation). func shouldEmitFunctionProperties(input *ast.FunctionDeclaration) bool { - if input.Body != nil { + if input.Body() != nil { return true } return !core.Every(input.Symbol.Declarations, func(decl *ast.Node) bool { - return !ast.IsFunctionDeclaration(decl) || decl.AsFunctionDeclaration().Body == nil + return !ast.IsFunctionDeclaration(decl) || decl.AsFunctionDeclaration().Body() == nil }) } diff --git a/tsc/internal/transformers/destructuring.go b/tsc/internal/transformers/destructuring.go index b3dc34e1b2260..1252a8aca1a41 100644 --- a/tsc/internal/transformers/destructuring.go +++ b/tsc/internal/transformers/destructuring.go @@ -205,12 +205,12 @@ func (f *flattener) flattenDestructuringAssignment(node *ast.Node, needsValue bo location := node.Loc var value *ast.Node if ast.IsDestructuringAssignment(node) { - value = node.AsBinaryExpression().Right - for ast.IsEmptyArrayLiteral(node.AsBinaryExpression().Left) || ast.IsEmptyObjectLiteral(node.AsBinaryExpression().Left) { + value = node.AsBinaryExpression().Right() + for ast.IsEmptyArrayLiteral(node.AsBinaryExpression().Left()) || ast.IsEmptyObjectLiteral(node.AsBinaryExpression().Left()) { if ast.IsDestructuringAssignment(value) { node = value location = node.Loc - value = node.AsBinaryExpression().Right + value = node.AsBinaryExpression().Right() } else { return f.tx.Visitor().VisitNode(value) } @@ -349,7 +349,7 @@ func (f *flattener) flattenObjectBindingOrAssignmentPattern(parent *ast.Node, pa } rhsValue := f.createDestructuringPropertyAccess(value, propertyName) if ast.IsComputedPropertyName(propertyName) { - computedTempVariables = append(computedTempVariables, rhsValue.AsElementAccessExpression().ArgumentExpression) + computedTempVariables = append(computedTempVariables, rhsValue.AsElementAccessExpression().ArgumentExpression()) } f.flattenBindingOrAssignmentElement(element, rhsValue, element.Loc, false) } @@ -466,15 +466,15 @@ func GetInitializerOfBindingOrAssignmentElement(bindingElement *ast.Node) *ast.N if ast.IsPropertyAssignment(bindingElement) { initializer := bindingElement.Initializer() if ast.IsAssignmentExpression(initializer, true) { - return initializer.AsBinaryExpression().Right + return initializer.AsBinaryExpression().Right() } return nil } if ast.IsShorthandPropertyAssignment(bindingElement) { - return bindingElement.AsShorthandPropertyAssignment().ObjectAssignmentInitializer + return bindingElement.AsShorthandPropertyAssignment().ObjectAssignmentInitializer() } if ast.IsAssignmentExpression(bindingElement, true) { - return bindingElement.AsBinaryExpression().Right + return bindingElement.AsBinaryExpression().Right() } if ast.IsSpreadElement(bindingElement) { return GetInitializerOfBindingOrAssignmentElement(bindingElement.Expression()) diff --git a/tsc/internal/transformers/estransforms/async.go b/tsc/internal/transformers/estransforms/async.go index 74a6aa18b3ef3..72d32282f200b 100644 --- a/tsc/internal/transformers/estransforms/async.go +++ b/tsc/internal/transformers/estransforms/async.go @@ -194,8 +194,8 @@ func (tx *asyncTransformer) visitAsyncBodyNode(node *ast.Node) *ast.Node { func (tx *asyncTransformer) visitCatchClauseInAsyncBody(node *ast.CatchClause) *ast.Node { catchClauseNames := &collections.Set[string]{} - if node.VariableDeclaration != nil { - tx.recordDeclarationName(node.VariableDeclaration, catchClauseNames) + if node.VariableDeclaration() != nil { + tx.recordDeclarationName(node.VariableDeclaration(), catchClauseNames) } // names declared in a catch variable are block scoped @@ -220,7 +220,7 @@ func (tx *asyncTransformer) visitCatchClauseInAsyncBody(node *ast.CatchClause) * } func (tx *asyncTransformer) visitVariableStatementInAsyncBody(node *ast.Node) *ast.Node { - declList := node.AsVariableStatement().DeclarationList + declList := node.AsVariableStatement().DeclarationList() if tx.isVariableDeclarationListWithCollidingName(declList) { expression := tx.visitVariableDeclarationListWithCollidingNames(declList.AsVariableDeclarationList(), false) if expression != nil { @@ -233,53 +233,53 @@ func (tx *asyncTransformer) visitVariableStatementInAsyncBody(node *ast.Node) *a func (tx *asyncTransformer) visitForInStatementInAsyncBody(node *ast.ForInOrOfStatement) *ast.Node { var visitedInitializer *ast.Node - if tx.isVariableDeclarationListWithCollidingName(node.Initializer) { - visitedInitializer = tx.visitVariableDeclarationListWithCollidingNames(node.Initializer.AsVariableDeclarationList(), true) + if tx.isVariableDeclarationListWithCollidingName(node.Initializer()) { + visitedInitializer = tx.visitVariableDeclarationListWithCollidingNames(node.Initializer().AsVariableDeclarationList(), true) } else { - visitedInitializer = tx.Visitor().VisitNode(node.Initializer) + visitedInitializer = tx.Visitor().VisitNode(node.Initializer()) } return tx.Factory().UpdateForInOrOfStatement( node, nil, /*awaitModifier*/ visitedInitializer, - tx.Visitor().VisitNode(node.Expression), - tx.asyncBodyVisitor.VisitEmbeddedStatement(node.Statement), + tx.Visitor().VisitNode(node.Expression()), + tx.asyncBodyVisitor.VisitEmbeddedStatement(node.Statement()), ) } func (tx *asyncTransformer) visitForOfStatementInAsyncBody(node *ast.ForInOrOfStatement) *ast.Node { var visitedInitializer *ast.Node - if tx.isVariableDeclarationListWithCollidingName(node.Initializer) { - visitedInitializer = tx.visitVariableDeclarationListWithCollidingNames(node.Initializer.AsVariableDeclarationList(), true) + if tx.isVariableDeclarationListWithCollidingName(node.Initializer()) { + visitedInitializer = tx.visitVariableDeclarationListWithCollidingNames(node.Initializer().AsVariableDeclarationList(), true) } else { - visitedInitializer = tx.Visitor().VisitNode(node.Initializer) + visitedInitializer = tx.Visitor().VisitNode(node.Initializer()) } return tx.Factory().UpdateForInOrOfStatement( node, - tx.Visitor().VisitNode(node.AwaitModifier), + tx.Visitor().VisitNode(node.AwaitModifier()), visitedInitializer, - tx.Visitor().VisitNode(node.Expression), - tx.asyncBodyVisitor.VisitEmbeddedStatement(node.Statement), + tx.Visitor().VisitNode(node.Expression()), + tx.asyncBodyVisitor.VisitEmbeddedStatement(node.Statement()), ) } func (tx *asyncTransformer) visitForStatementInAsyncBody(node *ast.ForStatement) *ast.Node { - initializer := node.Initializer + initializer := node.Initializer() var visitedInitializer *ast.Node if initializer != nil && tx.isVariableDeclarationListWithCollidingName(initializer) { visitedInitializer = tx.visitVariableDeclarationListWithCollidingNames(initializer.AsVariableDeclarationList(), false) } else { - visitedInitializer = tx.Visitor().VisitNode(node.Initializer) + visitedInitializer = tx.Visitor().VisitNode(node.Initializer()) } return tx.Factory().UpdateForStatement( node, visitedInitializer, - tx.Visitor().VisitNode(node.Condition), - tx.Visitor().VisitNode(node.Incrementor), - tx.asyncBodyVisitor.VisitEmbeddedStatement(node.Statement), + tx.Visitor().VisitNode(node.Condition()), + tx.Visitor().VisitNode(node.Incrementor()), + tx.asyncBodyVisitor.VisitEmbeddedStatement(node.Statement()), ) } @@ -293,7 +293,7 @@ func (tx *asyncTransformer) visitAwaitExpression(node *ast.AwaitExpression) *ast } yieldExpr := tx.Factory().NewYieldExpression( nil, /*asteriskToken*/ - tx.Visitor().VisitNode(node.Expression), + tx.Visitor().VisitNode(node.Expression()), ) yieldExpr.Loc = node.Loc tx.EmitContext().SetOriginal(yieldExpr, node.AsNode()) @@ -308,7 +308,7 @@ func (tx *asyncTransformer) visitConstructorDeclaration(node *ast.Node) *ast.Nod decl, tx.Visitor().VisitModifiers(decl.Modifiers()), nil, /*typeParameters*/ - tx.EmitContext().VisitParameters(decl.Parameters, tx.Visitor()), + tx.EmitContext().VisitParameters(decl.Parameters(), tx.Visitor()), nil, /*returnType*/ nil, /*fullSignature*/ tx.transformMethodBody(node), @@ -333,14 +333,14 @@ func (tx *asyncTransformer) visitMethodDeclaration(node *ast.Node) *ast.Node { parameters = tx.transformAsyncFunctionParameterList(node) body = tx.transformAsyncFunctionBody(node, parameters) } else { - parameters = tx.EmitContext().VisitParameters(decl.Parameters, tx.Visitor()) + parameters = tx.EmitContext().VisitParameters(decl.Parameters(), tx.Visitor()) body = tx.transformMethodBody(node) } updated := tx.Factory().UpdateMethodDeclaration( decl, tx.Visitor().VisitModifiers(decl.Modifiers()), - decl.AsteriskToken, + decl.AsteriskToken(), decl.Name(), nil, /*postfixToken*/ nil, /*typeParameters*/ @@ -362,7 +362,7 @@ func (tx *asyncTransformer) visitGetAccessorDeclaration(node *ast.Node) *ast.Nod tx.Visitor().VisitModifiers(decl.Modifiers()), decl.Name(), nil, /*typeParameters*/ - tx.EmitContext().VisitParameters(decl.Parameters, tx.Visitor()), + tx.EmitContext().VisitParameters(decl.Parameters(), tx.Visitor()), nil, /*returnType*/ nil, /*fullSignature*/ tx.transformMethodBody(node), @@ -380,7 +380,7 @@ func (tx *asyncTransformer) visitSetAccessorDeclaration(node *ast.Node) *ast.Nod tx.Visitor().VisitModifiers(decl.Modifiers()), decl.Name(), nil, /*typeParameters*/ - tx.EmitContext().VisitParameters(decl.Parameters, tx.Visitor()), + tx.EmitContext().VisitParameters(decl.Parameters(), tx.Visitor()), nil, /*returnType*/ nil, /*fullSignature*/ tx.transformMethodBody(node), @@ -405,14 +405,14 @@ func (tx *asyncTransformer) visitFunctionDeclaration(node *ast.Node) *ast.Node { parameters = tx.transformAsyncFunctionParameterList(node) body = tx.transformAsyncFunctionBody(node, parameters) } else { - parameters = tx.EmitContext().VisitParameters(decl.Parameters, tx.Visitor()) - body = tx.EmitContext().VisitFunctionBody(decl.Body, tx.Visitor()) + parameters = tx.EmitContext().VisitParameters(decl.Parameters(), tx.Visitor()) + body = tx.EmitContext().VisitFunctionBody(decl.Body(), tx.Visitor()) } updated := tx.Factory().UpdateFunctionDeclaration( decl, tx.Visitor().VisitModifiers(decl.Modifiers()), - decl.AsteriskToken, + decl.AsteriskToken(), tx.Visitor().VisitNode(decl.Name()), nil, /*typeParameters*/ parameters, @@ -440,14 +440,14 @@ func (tx *asyncTransformer) visitFunctionExpression(node *ast.Node) *ast.Node { parameters = tx.transformAsyncFunctionParameterList(node) body = tx.transformAsyncFunctionBody(node, parameters) } else { - parameters = tx.EmitContext().VisitParameters(decl.Parameters, tx.Visitor()) - body = tx.EmitContext().VisitFunctionBody(decl.Body, tx.Visitor()) + parameters = tx.EmitContext().VisitParameters(decl.Parameters(), tx.Visitor()) + body = tx.EmitContext().VisitFunctionBody(decl.Body(), tx.Visitor()) } updated := tx.Factory().UpdateFunctionExpression( decl, tx.Visitor().VisitModifiers(decl.Modifiers()), - decl.AsteriskToken, + decl.AsteriskToken(), tx.Visitor().VisitNode(decl.Name()), nil, /*typeParameters*/ parameters, @@ -483,8 +483,8 @@ func (tx *asyncTransformer) visitArrowFunction(node *ast.Node) *ast.Node { parameters = tx.transformAsyncFunctionParameterList(node) body = tx.transformAsyncFunctionBody(node, parameters) } else { - parameters = tx.EmitContext().VisitParameters(decl.Parameters, tx.Visitor()) - body = tx.EmitContext().VisitFunctionBody(decl.Body, tx.Visitor()) + parameters = tx.EmitContext().VisitParameters(decl.Parameters(), tx.Visitor()) + body = tx.EmitContext().VisitFunctionBody(decl.Body(), tx.Visitor()) } return tx.Factory().UpdateArrowFunction( @@ -494,7 +494,7 @@ func (tx *asyncTransformer) visitArrowFunction(node *ast.Node) *ast.Node { parameters, nil, /*returnType*/ nil, /*fullSignature*/ - decl.EqualsGreaterThanToken, + decl.EqualsGreaterThanToken(), body, ) } @@ -507,7 +507,7 @@ func (tx *asyncTransformer) recordDeclarationName(node *ast.Node, names *collect if ast.IsIdentifier(name) { names.Add(name.Text()) } else if ast.IsBindingPattern(name) { - for _, element := range name.AsBindingPattern().Elements.Nodes { + for _, element := range name.AsBindingPattern().Elements().Nodes { if !ast.IsOmittedExpression(element) { tx.recordDeclarationName(element, names) } @@ -519,22 +519,22 @@ func (tx *asyncTransformer) isVariableDeclarationListWithCollidingName(node *ast return node != nil && ast.IsVariableDeclarationList(node) && node.Flags&ast.NodeFlagsBlockScoped == 0 && - slices.ContainsFunc(node.AsVariableDeclarationList().Declarations.Nodes, tx.collidesWithParameterName) + slices.ContainsFunc(node.AsVariableDeclarationList().Declarations().Nodes, tx.collidesWithParameterName) } func (tx *asyncTransformer) visitVariableDeclarationListWithCollidingNames(node *ast.VariableDeclarationList, hasReceiver bool) *ast.Node { tx.hoistVariableDeclarationList(node) var variables []*ast.Node - for _, decl := range node.Declarations.Nodes { - if decl.AsVariableDeclaration().Initializer != nil { + for _, decl := range node.Declarations().Nodes { + if decl.AsVariableDeclaration().Initializer() != nil { variables = append(variables, decl) } } if len(variables) == 0 { if hasReceiver { - name := node.Declarations.Nodes[0].Name() + name := node.Declarations().Nodes[0].Name() var target *ast.Node if ast.IsBindingPattern(name) { target = transformers.ConvertBindingPatternToAssignmentPattern(tx.EmitContext(), name.AsBindingPattern()) @@ -554,7 +554,7 @@ func (tx *asyncTransformer) visitVariableDeclarationListWithCollidingNames(node } func (tx *asyncTransformer) hoistVariableDeclarationList(node *ast.VariableDeclarationList) { - for _, decl := range node.Declarations.Nodes { + for _, decl := range node.Declarations().Nodes { tx.hoistVariable(decl) } } @@ -567,7 +567,7 @@ func (tx *asyncTransformer) hoistVariable(node *ast.Node) { if ast.IsIdentifier(name) { tx.EmitContext().AddVariableDeclaration(name) } else if ast.IsBindingPattern(name) { - for _, element := range name.AsBindingPattern().Elements.Nodes { + for _, element := range name.AsBindingPattern().Elements().Nodes { if !ast.IsOmittedExpression(element) { tx.hoistVariable(element) } @@ -582,7 +582,7 @@ func (tx *asyncTransformer) transformInitializedVariable(node *ast.VariableDecla } else { target = node.Name() } - converted := tx.Factory().NewAssignmentExpression(target, node.Initializer) + converted := tx.Factory().NewAssignmentExpression(target, node.Initializer()) tx.EmitContext().SetSourceMapRange(converted, node.Loc) return tx.Visitor().VisitNode(converted) } @@ -596,7 +596,7 @@ func (tx *asyncTransformer) collidesWithParameterName(node *ast.Node) bool { return tx.enclosingFunctionParameterNames != nil && tx.enclosingFunctionParameterNames.Has(name.Text()) } if ast.IsBindingPattern(name) { - for _, element := range name.AsBindingPattern().Elements.Nodes { + for _, element := range name.AsBindingPattern().Elements().Nodes { if !ast.IsOmittedExpression(element) && tx.collidesWithParameterName(element) { return true } @@ -676,7 +676,7 @@ func (tx *asyncTransformer) transformAsyncFunctionParameterList(node *ast.Node) var newParameters []*ast.Node for _, parameter := range node.Parameters() { param := parameter.AsParameterDeclaration() - if param.Initializer != nil || param.DotDotDotToken != nil { + if param.Initializer() != nil || param.DotDotDotToken() != nil { // for an arrow function, capture the remaining arguments in a rest parameter. // for any other function/method this isn't necessary as we can just use `arguments`. if node.Kind == ast.KindArrowFunction { @@ -750,7 +750,7 @@ func (tx *asyncTransformer) transformAsyncFunctionBody(node *ast.Node, outerPara } originalParameter := param.AsParameterDeclaration() outerParameter := outerParameters.Nodes[i].AsParameterDeclaration() - if originalParameter.Initializer != nil || originalParameter.DotDotDotToken != nil { + if originalParameter.Initializer() != nil || originalParameter.DotDotDotToken() != nil { parameterBindings = append(parameterBindings, tx.Factory().NewSpreadElement(outerParameter.Name())) break } @@ -901,14 +901,14 @@ func assignmentTargetContainsSuperProperty(node *ast.Node) bool { case ast.KindPropertyAccessExpression, ast.KindElementAccessExpression: return node.Expression().Kind == ast.KindSuperKeyword case ast.KindParenthesizedExpression: - return assignmentTargetContainsSuperProperty(node.AsParenthesizedExpression().Expression) + return assignmentTargetContainsSuperProperty(node.AsParenthesizedExpression().Expression()) case ast.KindArrayLiteralExpression: - return slices.ContainsFunc(node.AsArrayLiteralExpression().Elements.Nodes, assignmentTargetContainsSuperProperty) + return slices.ContainsFunc(node.AsArrayLiteralExpression().Elements().Nodes, assignmentTargetContainsSuperProperty) case ast.KindObjectLiteralExpression: - for _, prop := range node.AsObjectLiteralExpression().Properties.Nodes { + for _, prop := range node.AsObjectLiteralExpression().Properties().Nodes { switch prop.Kind { case ast.KindPropertyAssignment: - if assignmentTargetContainsSuperProperty(prop.AsPropertyAssignment().Initializer) { + if assignmentTargetContainsSuperProperty(prop.AsPropertyAssignment().Initializer()) { return true } case ast.KindShorthandPropertyAssignment: @@ -916,13 +916,13 @@ func assignmentTargetContainsSuperProperty(node *ast.Node) bool { return true } case ast.KindSpreadAssignment: - if assignmentTargetContainsSuperProperty(prop.AsSpreadAssignment().Expression) { + if assignmentTargetContainsSuperProperty(prop.AsSpreadAssignment().Expression()) { return true } } } case ast.KindSpreadElement: - return assignmentTargetContainsSuperProperty(node.AsSpreadElement().Expression) + return assignmentTargetContainsSuperProperty(node.AsSpreadElement().Expression()) } return false } @@ -952,7 +952,7 @@ func (tx *asyncTransformer) getOriginalIfFunctionLike(node *ast.Node) *ast.Node func isSimpleParameterList(params []*ast.Node) bool { for _, param := range params { p := param.AsParameterDeclaration() - if p.Initializer != nil || !ast.IsIdentifier(p.Name()) { + if p.Initializer() != nil || !ast.IsIdentifier(p.Name()) { return false } } diff --git a/tsc/internal/transformers/estransforms/classfields.go b/tsc/internal/transformers/estransforms/classfields.go index 68dc3950413d9..0117a844e7af9 100644 --- a/tsc/internal/transformers/estransforms/classfields.go +++ b/tsc/internal/transformers/estransforms/classfields.go @@ -393,7 +393,7 @@ func (tx *classFieldsTransformer) visitDestructuringAssignmentTarget(node *ast.N if data.classConstructor != nil && data.superClassReference != nil { var name *ast.Expression if ast.IsElementAccessExpression(node) { - name = tx.Visitor().VisitNode(node.AsElementAccessExpression().ArgumentExpression) + name = tx.Visitor().VisitNode(node.AsElementAccessExpression().ArgumentExpression()) } else if ast.IsPropertyAccessExpression(node) && ast.IsIdentifier(node.AsPropertyAccessExpression().Name()) { name = tx.Factory().NewStringLiteralFromNode(node.AsPropertyAccessExpression().Name()) } @@ -490,9 +490,9 @@ func (tx *classFieldsTransformer) visitPrivateIdentifier(node *ast.Node) *ast.No // transformPrivateIdentifierInInExpression visits `#id in expr`. func (tx *classFieldsTransformer) transformPrivateIdentifierInInExpression(node *ast.BinaryExpression) *ast.Node { - info := tx.accessPrivateIdentifier(node.Left) + info := tx.accessPrivateIdentifier(node.Left()) if info != nil { - receiver := tx.Visitor().VisitNode(node.Right) + receiver := tx.Visitor().VisitNode(node.Right()) result := tx.Factory().NewClassPrivateFieldInHelper(info.brandCheckIdentifier, receiver) tx.EmitContext().SetOriginal(result, node.AsNode()) return result @@ -647,7 +647,7 @@ func (tx *classFieldsTransformer) visitComputedPropertyName(node *ast.ComputedPr if tx.lexicalEnvironment != nil && tx.lexicalEnvironment.previous != nil { tx.lexicalEnvironment = tx.lexicalEnvironment.previous } - expression := tx.Visitor().VisitNode(node.Expression) + expression := tx.Visitor().VisitNode(node.Expression()) tx.lexicalEnvironment = savedLexicalEnvironment tx.insideComputedPropertyName = savedInsideComputedPropertyName return tx.Factory().UpdateComputedPropertyName(node, tx.injectPendingExpressions(expression)) @@ -702,7 +702,7 @@ func (tx *classFieldsTransformer) visitMethodOrAccessorDeclaration(node *ast.Nod params := tx.Visitor().VisitNodes(node.ParameterList()) tx.inIterationStatement = saved - funcExpr := tx.Factory().NewFunctionExpression(modifiers, node.BodyData().AsteriskToken, functionName, nil, params, nil, nil, body) + funcExpr := tx.Factory().NewFunctionExpression(modifiers, node.BodyData().AsteriskToken(), functionName, nil, params, nil, nil, body) assignment := tx.Factory().NewAssignmentExpression(functionName, funcExpr) tx.addPendingExpressions(assignment) } @@ -843,7 +843,7 @@ func (tx *classFieldsTransformer) transformAutoAccessor(node *ast.PropertyDeclar cacheAssignment := findComputedPropertyNameCacheAssignment(tx.EmitContext(), name) if cacheAssignment != nil { getterName = tx.Factory().UpdateComputedPropertyName(name.AsComputedPropertyName(), tx.Visitor().VisitNode(name.Expression())) - setterName = tx.Factory().UpdateComputedPropertyName(name.AsComputedPropertyName(), cacheAssignment.Left) + setterName = tx.Factory().UpdateComputedPropertyName(name.AsComputedPropertyName(), cacheAssignment.Left()) } else { temp := tx.Factory().NewTempVariable() tx.EmitContext().SetSourceMapRange(temp, name.Expression().Loc) @@ -857,7 +857,7 @@ func (tx *classFieldsTransformer) transformAutoAccessor(node *ast.PropertyDeclar } modifiers := tx.modifierVisitor.VisitModifiers(node.Modifiers()) - backingField := createAccessorPropertyBackingField(tx.Factory(), node, modifiers, node.Initializer) + backingField := createAccessorPropertyBackingField(tx.Factory(), node, modifiers, node.Initializer()) tx.EmitContext().SetOriginal(backingField, node.AsNode()) tx.EmitContext().AddEmitFlags(backingField, printer.EFNoComments) tx.EmitContext().SetSourceMapRange(backingField, sourceMapRange) @@ -942,7 +942,7 @@ func (tx *classFieldsTransformer) transformPrivateFieldInitializer(node *ast.Pro tx.visitPropertyName(node.Name()), nil, /*postfixToken*/ nil, /*typeNode*/ - tx.Visitor().VisitNode(node.Initializer), + tx.Visitor().VisitNode(node.Initializer()), ) } @@ -950,7 +950,7 @@ func (tx *classFieldsTransformer) transformPublicFieldInitializer(node *ast.Prop if tx.shouldTransformInitializers && !ast.IsAutoAccessorPropertyDeclaration(node.AsNode()) { // Elide the property declaration; the initializer will be moved to the constructor. // For computed property names, we still need to emit the expression. - expr := tx.getPropertyNameExpressionIfNeeded(node.Name(), node.Initializer != nil || tx.compilerOptions.GetUseDefineForClassFields()) + expr := tx.getPropertyNameExpressionIfNeeded(node.Name(), node.Initializer() != nil || tx.compilerOptions.GetUseDefineForClassFields()) if expr != nil { for e := range flattenCommaList(expr) { tx.addPendingExpressions(e) @@ -986,7 +986,7 @@ func (tx *classFieldsTransformer) transformPublicFieldInitializer(node *ast.Prop tx.visitPropertyName(node.Name()), nil, /*postfixToken*/ nil, /*typeNode*/ - tx.Visitor().VisitNode(node.Initializer), + tx.Visitor().VisitNode(node.Initializer()), ) } @@ -1065,7 +1065,7 @@ func (tx *classFieldsTransformer) visitPropertyAccessExpression(node *ast.Proper if ast.IsPrivateIdentifier(node.Name()) { info := tx.accessPrivateIdentifier(node.Name()) if info != nil { - result := tx.createPrivateIdentifierAccess(info, node.Expression) + result := tx.createPrivateIdentifierAccess(info, node.Expression()) tx.EmitContext().SetOriginal(result, node.AsNode()) result.Loc = node.Loc return result @@ -1086,8 +1086,8 @@ func (tx *classFieldsTransformer) visitPropertyAccessExpression(node *ast.Proper tx.Factory().NewStringLiteralFromNode(node.Name()), data.classConstructor, ) - tx.EmitContext().SetOriginal(superProperty, node.Expression) - superProperty.Loc = node.Expression.Loc + tx.EmitContext().SetOriginal(superProperty, node.Expression()) + superProperty.Loc = node.Expression().Loc return superProperty } } @@ -1106,9 +1106,9 @@ func (tx *classFieldsTransformer) visitPropertyAccessExpression(node *ast.Proper // leaving the name unchanged. This prevents the name from being treated as a standalone identifier // reference and incorrectly substituted with a class alias. func (tx *classFieldsTransformer) visitPropertyAccessExpressionForSubstitution(node *ast.PropertyAccessExpression) *ast.Node { - expression := tx.Visitor().VisitNode(node.Expression) - if expression != node.Expression { - return tx.Factory().UpdatePropertyAccessExpression(node, expression, node.QuestionDotToken, node.Name(), node.Flags) + expression := tx.Visitor().VisitNode(node.Expression()) + if expression != node.Expression() { + return tx.Factory().UpdatePropertyAccessExpression(node, expression, node.QuestionDotToken(), node.Name(), node.Flags) } return node.AsNode() } @@ -1126,11 +1126,11 @@ func (tx *classFieldsTransformer) visitElementAccessExpression(node *ast.Element // converts `super[x]` into `Reflect.get(_baseTemp, x, _classTemp)` superProperty := tx.Factory().NewReflectGetCall( data.superClassReference, - tx.Visitor().VisitNode(node.ArgumentExpression), + tx.Visitor().VisitNode(node.ArgumentExpression()), data.classConstructor, ) - tx.EmitContext().SetOriginal(superProperty, node.Expression) - superProperty.Loc = node.Expression.Loc + tx.EmitContext().SetOriginal(superProperty, node.Expression()) + superProperty.Loc = node.Expression().Loc return superProperty } } @@ -1142,10 +1142,10 @@ func (tx *classFieldsTransformer) visitPreOrPostfixUnaryExpression(node *ast.Nod var operand *ast.Node if ast.IsPrefixUnaryExpression(node) { operator = node.AsPrefixUnaryExpression().Operator - operand = node.AsPrefixUnaryExpression().Operand + operand = node.AsPrefixUnaryExpression().Operand() } else { operator = node.AsPostfixUnaryExpression().Operator - operand = node.AsPostfixUnaryExpression().Operand + operand = node.AsPostfixUnaryExpression().Operand() } if operator == ast.KindPlusPlusToken || operator == ast.KindMinusMinusToken { @@ -1207,13 +1207,13 @@ func (tx *classFieldsTransformer) visitPreOrPostfixUnaryExpression(node *ast.Nod setterName = getterName } } else if ast.IsElementAccessExpression(operandSkipped) { - if transformers.IsSimpleInlineableExpression(operandSkipped.AsElementAccessExpression().ArgumentExpression) { - getterName = operandSkipped.AsElementAccessExpression().ArgumentExpression + if transformers.IsSimpleInlineableExpression(operandSkipped.AsElementAccessExpression().ArgumentExpression()) { + getterName = operandSkipped.AsElementAccessExpression().ArgumentExpression() setterName = getterName } else { getterName = tx.Factory().NewTempVariable() tx.EmitContext().AddVariableDeclaration(getterName) - setterName = tx.Factory().NewAssignmentExpression(getterName, tx.Visitor().VisitNode(operandSkipped.AsElementAccessExpression().ArgumentExpression)) + setterName = tx.Factory().NewAssignmentExpression(getterName, tx.Visitor().VisitNode(operandSkipped.AsElementAccessExpression().ArgumentExpression())) } } if setterName != nil && getterName != nil { @@ -1242,12 +1242,12 @@ func (tx *classFieldsTransformer) visitPreOrPostfixUnaryExpression(node *ast.Nod } func (tx *classFieldsTransformer) visitForStatement(node *ast.ForStatement) *ast.Node { - initializer := tx.discardedValueVisitor.VisitNode(node.Initializer) - condition := tx.Visitor().VisitNode(node.Condition) - incrementor := tx.discardedValueVisitor.VisitNode(node.Incrementor) + initializer := tx.discardedValueVisitor.VisitNode(node.Initializer()) + condition := tx.Visitor().VisitNode(node.Condition()) + incrementor := tx.discardedValueVisitor.VisitNode(node.Incrementor()) saved := tx.inIterationStatement tx.inIterationStatement = true - body := tx.EmitContext().VisitIterationBody(node.Statement, tx.Visitor()) + body := tx.EmitContext().VisitIterationBody(node.Statement(), tx.Visitor()) tx.inIterationStatement = saved return tx.Factory().UpdateForStatement(node, initializer, condition, incrementor, body) } @@ -1257,12 +1257,12 @@ func (tx *classFieldsTransformer) visitExpressionStatement(node *ast.ExpressionS // ExpressionStatement (e.g., `#;`). This is error-recovery output from the parser // for invalid syntax. Keeping it ensures the runtime throws a SyntaxError rather // than silently succeeding with an empty statement. - if ast.IsPrivateIdentifier(node.Expression) && tx.shouldTransformPrivateElementsOrClassStaticBlocks { + if ast.IsPrivateIdentifier(node.Expression()) && tx.shouldTransformPrivateElementsOrClassStaticBlocks { return node.AsNode() } return tx.Factory().UpdateExpressionStatement( node, - tx.discardedValueVisitor.VisitNode(node.Expression), + tx.discardedValueVisitor.VisitNode(node.Expression()), ) } @@ -1281,22 +1281,22 @@ func (tx *classFieldsTransformer) createCopiableReceiverExpr(receiver *ast.Expre } func (tx *classFieldsTransformer) visitCallExpression(node *ast.CallExpression) *ast.Node { - if ast.IsPropertyAccessExpression(node.Expression) && ast.IsPrivateIdentifier(node.Expression.AsPropertyAccessExpression().Name()) && - tx.accessPrivateIdentifier(node.Expression.AsPropertyAccessExpression().Name()) != nil { + if ast.IsPropertyAccessExpression(node.Expression()) && ast.IsPrivateIdentifier(node.Expression().AsPropertyAccessExpression().Name()) && + tx.accessPrivateIdentifier(node.Expression().AsPropertyAccessExpression().Name()) != nil { // obj.#x() // Transform call expressions of private names to properly bind the `this` parameter. - thisArg, target := tx.createCallBinding(node.Expression) + thisArg, target := tx.createCallBinding(node.Expression()) visitedTarget := tx.Visitor().VisitNode(target) visitedThisArg := tx.Visitor().VisitNode(thisArg) - visitedArgs := tx.Visitor().VisitNodes(node.Arguments) + visitedArgs := tx.Visitor().VisitNodes(node.Arguments()) allArgs := make([]*ast.Node, 0, 1+len(visitedArgs.Nodes)) allArgs = append(allArgs, visitedThisArg) allArgs = append(allArgs, visitedArgs.Nodes...) if node.Flags&ast.NodeFlagsOptionalChain != 0 { return tx.Factory().UpdateCallExpression( node, - tx.Factory().NewPropertyAccessExpression(visitedTarget, node.QuestionDotToken, tx.Factory().NewIdentifier("call"), ast.NodeFlagsOptionalChain), + tx.Factory().NewPropertyAccessExpression(visitedTarget, node.QuestionDotToken(), tx.Factory().NewIdentifier("call"), ast.NodeFlagsOptionalChain), nil, /*questionDotToken*/ nil, /*typeArguments*/ tx.Factory().NewNodeList(allArgs), @@ -1314,7 +1314,7 @@ func (tx *classFieldsTransformer) visitCallExpression(node *ast.CallExpression) } if tx.shouldTransformSuperInStaticInitializers && tx.currentClassElement != nil && - ast.IsSuperProperty(node.Expression) && + ast.IsSuperProperty(node.Expression()) && isStaticPropertyDeclarationOrClassStaticBlock(tx.currentClassElement) && tx.lexicalEnvironment != nil && tx.lexicalEnvironment.data != nil && tx.lexicalEnvironment.data.classConstructor != nil { @@ -1323,9 +1323,9 @@ func (tx *classFieldsTransformer) visitCallExpression(node *ast.CallExpression) // converts `super.f(...)` into `Reflect.get(_baseTemp, "f", _classTemp).call(_classTemp, ...)` invocation := tx.Factory().NewFunctionCallCall( - tx.Visitor().VisitNode(node.Expression), + tx.Visitor().VisitNode(node.Expression()), tx.lexicalEnvironment.data.classConstructor, - tx.Visitor().VisitNodes(node.Arguments).Nodes, + tx.Visitor().VisitNodes(node.Arguments()).Nodes, ) tx.EmitContext().SetOriginal(invocation, node.AsNode()) invocation.Loc = node.Loc @@ -1336,10 +1336,10 @@ func (tx *classFieldsTransformer) visitCallExpression(node *ast.CallExpression) } func (tx *classFieldsTransformer) visitTaggedTemplateExpression(node *ast.TaggedTemplateExpression) *ast.Node { - if ast.IsPropertyAccessExpression(node.Tag) && ast.IsPrivateIdentifier(node.Tag.AsPropertyAccessExpression().Name()) && - tx.accessPrivateIdentifier(node.Tag.AsPropertyAccessExpression().Name()) != nil { + if ast.IsPropertyAccessExpression(node.Tag()) && ast.IsPrivateIdentifier(node.Tag().AsPropertyAccessExpression().Name()) && + tx.accessPrivateIdentifier(node.Tag().AsPropertyAccessExpression().Name()) != nil { // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access. - thisArg, target := tx.createCallBinding(node.Tag) + thisArg, target := tx.createCallBinding(node.Tag()) bindExpr := tx.Factory().NewCallExpression( tx.Factory().NewPropertyAccessExpression(tx.Visitor().VisitNode(target), nil, tx.Factory().NewIdentifier("bind"), ast.NodeFlagsNone), nil, /*questionDotToken*/ @@ -1352,19 +1352,19 @@ func (tx *classFieldsTransformer) visitTaggedTemplateExpression(node *ast.Tagged bindExpr, nil, /*questionDotToken*/ nil, /*typeArguments*/ - tx.Visitor().VisitNode(node.Template), + tx.Visitor().VisitNode(node.Template()), node.Flags, ) } if tx.shouldTransformSuperInStaticInitializers && tx.currentClassElement != nil && - ast.IsSuperProperty(node.Tag) && + ast.IsSuperProperty(node.Tag()) && isStaticPropertyDeclarationOrClassStaticBlock(tx.currentClassElement) && tx.lexicalEnvironment != nil && tx.lexicalEnvironment.data != nil && tx.lexicalEnvironment.data.classConstructor != nil { // converts `` super.f`x` `` into `` Reflect.get(_baseTemp, "f", _classTemp).bind(_classTemp)`x` `` invocation := tx.Factory().NewFunctionBindCall( - tx.Visitor().VisitNode(node.Tag), + tx.Visitor().VisitNode(node.Tag()), tx.lexicalEnvironment.data.classConstructor, nil, ) @@ -1375,7 +1375,7 @@ func (tx *classFieldsTransformer) visitTaggedTemplateExpression(node *ast.Tagged invocation, nil, /*questionDotToken*/ nil, /*typeArguments*/ - tx.Visitor().VisitNode(node.Template), + tx.Visitor().VisitNode(node.Template()), node.Flags, ) } @@ -1386,12 +1386,12 @@ func (tx *classFieldsTransformer) visitTaggedTemplateExpression(node *ast.Tagged func (tx *classFieldsTransformer) transformClassStaticBlockDeclaration(node *ast.Node) *ast.Expression { if tx.shouldTransformPrivateElementsOrClassStaticBlocks { if isClassThisAssignmentBlock(tx.EmitContext(), node) { - result := tx.Visitor().VisitNode(node.AsClassStaticBlockDeclaration().Body.AsBlock().Statements.Nodes[0].Expression()) + result := tx.Visitor().VisitNode(node.AsClassStaticBlockDeclaration().Body().AsBlock().Statements().Nodes[0].Expression()) // If the generated `_classThis` assignment is a noop (i.e., `_classThis = _classThis`), we can // eliminate the expression if ast.IsAssignmentExpression(result, true /*excludeCompoundAssignment*/) { binary := result.AsBinaryExpression() - if binary.Left == binary.Right { + if binary.Left() == binary.Right() { return nil } } @@ -1399,11 +1399,11 @@ func (tx *classFieldsTransformer) transformClassStaticBlockDeclaration(node *ast } if isClassNamedEvaluationHelperBlock(tx.EmitContext(), node) { - return tx.Visitor().VisitNode(node.AsClassStaticBlockDeclaration().Body.AsBlock().Statements.Nodes[0].Expression()) + return tx.Visitor().VisitNode(node.AsClassStaticBlockDeclaration().Body().AsBlock().Statements().Nodes[0].Expression()) } tx.EmitContext().StartVariableEnvironment() - statements := tx.setCurrentClassElementAndVisitStatements(node, node.AsClassStaticBlockDeclaration().Body.AsBlock().Statements.Nodes) + statements := tx.setCurrentClassElementAndVisitStatements(node, node.AsClassStaticBlockDeclaration().Body().AsBlock().Statements().Nodes) statements = tx.EmitContext().EndAndMergeVariableEnvironment(statements) iife := tx.Factory().NewImmediatelyInvokedArrowFunction(statements) @@ -1412,7 +1412,7 @@ func (tx *classFieldsTransformer) transformClassStaticBlockDeclaration(node *ast tx.EmitContext().AddEmitFlags(arrowFunction, printer.EFNoLexicalArguments) // Preserve the statement list source range so the printer can emit detached comments // (e.g., `// do` inside an otherwise empty static block) - arrowFunction.AsArrowFunction().Body.AsBlock().Statements.Loc = node.AsClassStaticBlockDeclaration().Body.AsBlock().Statements.Loc + arrowFunction.AsArrowFunction().Body().AsBlock().Statements().Loc = node.AsClassStaticBlockDeclaration().Body().AsBlock().Statements().Loc tx.EmitContext().SetOriginal(iife, node) tx.EmitContext().AssignSourceMapRange(iife, node) tx.EmitContext().AddEmitFlags(arrowFunction, printer.EFNoLexicalThis) @@ -1459,10 +1459,10 @@ func (tx *classFieldsTransformer) visitBinaryExpression(node *ast.BinaryExpressi updated := tx.Factory().UpdateBinaryExpression( node, nil, - tx.assignmentTargetVisitor.VisitNode(node.Left), + tx.assignmentTargetVisitor.VisitNode(node.Left()), nil, - node.OperatorToken, - tx.Visitor().VisitNode(node.Right), + node.OperatorToken(), + tx.Visitor().VisitNode(node.Right()), ) var result *ast.Expression if len(tx.pendingExpressions) > 0 { @@ -1507,18 +1507,18 @@ func (tx *classFieldsTransformer) visitBinaryExpression(node *ast.BinaryExpressi debug.Assert(node.AsNode() != nil && ast.IsAssignmentExpression(node.AsNode(), false)) } - left := ast.SkipOuterExpressions(node.Left, ast.OEKPartiallyEmittedExpressions|ast.OEKParentheses) + left := ast.SkipOuterExpressions(node.Left(), ast.OEKPartiallyEmittedExpressions|ast.OEKParentheses) if ast.IsPropertyAccessExpression(left) && ast.IsPrivateIdentifier(left.Name()) { // obj.#x = ... info := tx.accessPrivateIdentifier(left.Name()) if info != nil { - result := tx.createPrivateIdentifierAssignment(info, left.Expression(), node.Right, node.OperatorToken.Kind) + result := tx.createPrivateIdentifierAssignment(info, left.Expression(), node.Right(), node.OperatorToken().Kind) tx.EmitContext().SetOriginal(result, node.AsNode()) result.Loc = node.Loc return result } } else if tx.shouldTransformSuperInStaticInitializers && tx.currentClassElement != nil && - ast.IsSuperProperty(node.Left) && + ast.IsSuperProperty(node.Left()) && isStaticPropertyDeclarationOrClassStaticBlock(tx.currentClassElement) && tx.lexicalEnvironment != nil && tx.lexicalEnvironment.data != nil { // super.x = ... @@ -1530,18 +1530,18 @@ func (tx *classFieldsTransformer) visitBinaryExpression(node *ast.BinaryExpressi return tx.Factory().UpdateBinaryExpression( node, nil, - tx.visitInvalidSuperProperty(node.Left), + tx.visitInvalidSuperProperty(node.Left()), nil, - node.OperatorToken, - tx.Visitor().VisitNode(node.Right), + node.OperatorToken(), + tx.Visitor().VisitNode(node.Right()), ) } if data.classConstructor != nil && data.superClassReference != nil { var setterName *ast.Expression - if ast.IsElementAccessExpression(node.Left) { - setterName = tx.Visitor().VisitNode(node.Left.AsElementAccessExpression().ArgumentExpression) - } else if ast.IsPropertyAccessExpression(node.Left) && ast.IsIdentifier(node.Left.AsPropertyAccessExpression().Name()) { - setterName = tx.Factory().NewStringLiteralFromNode(node.Left.AsPropertyAccessExpression().Name()) + if ast.IsElementAccessExpression(node.Left()) { + setterName = tx.Visitor().VisitNode(node.Left().AsElementAccessExpression().ArgumentExpression()) + } else if ast.IsPropertyAccessExpression(node.Left()) && ast.IsIdentifier(node.Left().AsPropertyAccessExpression().Name()) { + setterName = tx.Factory().NewStringLiteralFromNode(node.Left().AsPropertyAccessExpression().Name()) } if setterName != nil { // converts `super.x = 1` into `(Reflect.set(_baseTemp, "x", _a = 1, _classTemp), _a)` @@ -1549,8 +1549,8 @@ func (tx *classFieldsTransformer) visitBinaryExpression(node *ast.BinaryExpressi // converts `super.x += 1` into `(Reflect.set(_baseTemp, "x", _a = Reflect.get(_baseTemp, "x", _classtemp) + 1, _classTemp), _a)` // converts `super[f()] += 1` into `(Reflect.set(_baseTemp, _a = f(), _b = Reflect.get(_baseTemp, _a, _classtemp) + 1, _classTemp), _b)` - expression := tx.Visitor().VisitNode(node.Right) - if ast.IsCompoundAssignment(node.OperatorToken.Kind) { + expression := tx.Visitor().VisitNode(node.Right()) + if ast.IsCompoundAssignment(node.OperatorToken().Kind) { getterName := setterName if !transformers.IsSimpleInlineableExpression(setterName) { getterName = tx.Factory().NewTempVariable() @@ -1562,13 +1562,13 @@ func (tx *classFieldsTransformer) visitBinaryExpression(node *ast.BinaryExpressi getterName, data.classConstructor, ) - tx.EmitContext().SetOriginal(superPropertyGet, node.Left) - superPropertyGet.Loc = node.Left.Loc + tx.EmitContext().SetOriginal(superPropertyGet, node.Left()) + superPropertyGet.Loc = node.Left().Loc expression = tx.Factory().NewBinaryExpression( nil, superPropertyGet, nil, - tx.Factory().NewToken(transformers.GetNonAssignmentOperatorForCompoundAssignment(node.OperatorToken.Kind)), + tx.Factory().NewToken(transformers.GetNonAssignmentOperatorForCompoundAssignment(node.OperatorToken().Kind)), expression, ) expression.Loc = node.Loc @@ -1603,7 +1603,7 @@ func (tx *classFieldsTransformer) visitBinaryExpression(node *ast.BinaryExpressi } } - if node.OperatorToken.Kind == ast.KindInKeyword && ast.IsPrivateIdentifier(node.Left) { + if node.OperatorToken().Kind == ast.KindInKeyword && ast.IsPrivateIdentifier(node.Left()) { // #x in obj return tx.transformPrivateIdentifierInInExpression(node) } @@ -1617,10 +1617,10 @@ func (tx *classFieldsTransformer) visitParenthesizedExpression(node *ast.Parenth // ... // 2. Return ? NamedEvaluation of |Expression| with argument _name_. if discarded { - expression := tx.discardedValueVisitor.VisitNode(node.Expression) + expression := tx.discardedValueVisitor.VisitNode(node.Expression()) return tx.Factory().UpdateParenthesizedExpression(node, expression) } - expression := tx.Visitor().VisitNode(node.Expression) + expression := tx.Visitor().VisitNode(node.Expression()) return tx.Factory().UpdateParenthesizedExpression(node, expression) } @@ -1713,7 +1713,7 @@ func (tx *classFieldsTransformer) memberContainsConstructorReference(member *ast // Check only the body/initializer of the member, not the name (which may be // a computed property name that shouldn't trigger alias substitution). if ast.IsClassStaticBlockDeclaration(member) { - body := member.AsClassStaticBlockDeclaration().Body + body := member.AsClassStaticBlockDeclaration().Body() if body != nil && check(body.AsNode()) { return true } @@ -1825,7 +1825,7 @@ func (tx *classFieldsTransformer) visitExpressionWithTypeArgumentsInHeritageClau tx.getClassLexicalEnvironment().superClassReference = temp return tx.Factory().UpdateExpressionWithTypeArguments( node, - tx.Factory().NewAssignmentExpression(temp, tx.Visitor().VisitNode(node.Expression)), + tx.Factory().NewAssignmentExpression(temp, tx.Visitor().VisitNode(node.Expression())), nil, /*typeArguments*/ ) } @@ -1939,7 +1939,7 @@ func (tx *classFieldsTransformer) visitClassDeclarationInNewClassLexicalEnvironm } modifiers := tx.modifierVisitor.VisitModifiers(classDecl.Modifiers()) - heritageClauses := tx.heritageClauseVisitor.VisitNodes(classDecl.HeritageClauses) + heritageClauses := tx.heritageClauseVisitor.VisitNodes(classDecl.HeritageClauses()) members, membersPrologue := tx.transformClassMembers(node) var statements []*ast.Node @@ -2087,7 +2087,7 @@ func (tx *classFieldsTransformer) visitClassExpressionInNewClassLexicalEnvironme } modifiers := tx.modifierVisitor.VisitModifiers(classExpr.Modifiers()) - heritageClauses := tx.heritageClauseVisitor.VisitNodes(classExpr.HeritageClauses) + heritageClauses := tx.heritageClauseVisitor.VisitNodes(classExpr.HeritageClauses()) members, membersPrologue := tx.transformClassMembers(node) if deferTempDeclaration { @@ -2381,7 +2381,7 @@ func (tx *classFieldsTransformer) transformConstructor(constructor *ast.Construc var parameters *ast.NodeList if constructor != nil { - parameters = tx.Visitor().VisitNodes(constructor.Parameters) + parameters = tx.Visitor().VisitNodes(constructor.Parameters()) } body := tx.transformConstructorBody(container, constructor, isDerivedClass) @@ -2439,10 +2439,10 @@ func (tx *classFieldsTransformer) transformConstructorBodyWorker( statementOffset = superStatementIndex + 1 if ast.IsTryStatement(superStatement) { - tryBlock := superStatement.AsTryStatement().TryBlock.AsBlock() + tryBlock := superStatement.AsTryStatement().TryBlock().AsBlock() tryBlockStatements := tx.transformConstructorBodyWorker( nil, - tryBlock.Statements.Nodes, + tryBlock.Statements().Nodes, 0, /*statementOffset*/ superPath, superPathDepth+1, @@ -2450,10 +2450,10 @@ func (tx *classFieldsTransformer) transformConstructorBodyWorker( constructor, ) tryStatementList := tx.Factory().NewNodeList(tryBlockStatements) - tryStatementList.Loc = tryBlock.Statements.Loc + tryStatementList.Loc = tryBlock.Statements().Loc - catchClause := tx.Visitor().VisitNode(superStatement.AsTryStatement().CatchClause) - finallyBlock := tx.Visitor().VisitNode(superStatement.AsTryStatement().FinallyBlock) + catchClause := tx.Visitor().VisitNode(superStatement.AsTryStatement().CatchClause()) + finallyBlock := tx.Visitor().VisitNode(superStatement.AsTryStatement().FinallyBlock()) updated := tx.Factory().UpdateTryStatement( superStatement.AsTryStatement(), @@ -2551,11 +2551,11 @@ func (tx *classFieldsTransformer) transformConstructorBody(container *ast.Node, initializerStatements = tx.addPropertyOrClassStaticBlockStatements(initializerStatements, properties, receiver) } - if constructor != nil && constructor.Body != nil { - body := constructor.Body.AsBlock() + if constructor != nil && constructor.Body() != nil { + body := constructor.Body().AsBlock() // Copy prologue - for _, stmt := range body.Statements.Nodes { + for _, stmt := range body.Statements().Nodes { if ast.IsPrologueDirective(stmt) { statements = append(statements, stmt) } else { @@ -2564,14 +2564,14 @@ func (tx *classFieldsTransformer) transformConstructorBody(container *ast.Node, } statementOffset := len(statements) - superPath := transformers.FindSuperStatementIndexPath(body.Statements.Nodes, statementOffset) + superPath := transformers.FindSuperStatementIndexPath(body.Statements().Nodes, statementOffset) if len(superPath) > 0 { - statements = tx.transformConstructorBodyWorker(statements, body.Statements.Nodes, statementOffset, superPath, 0, initializerStatements, constructor) + statements = tx.transformConstructorBodyWorker(statements, body.Statements().Nodes, statementOffset, superPath, 0, initializerStatements, constructor) } else { // parameter-property assignments should occur immediately after the prologue and `super()`, // so only count the statements that immediately follow. - for statementOffset < len(body.Statements.Nodes) { - stmt := body.Statements.Nodes[statementOffset] + for statementOffset < len(body.Statements().Nodes) { + stmt := body.Statements().Nodes[statementOffset] orig := tx.EmitContext().MostOriginal(stmt) if ast.IsParameterPropertyDeclaration(orig, constructor.AsNode()) { statementOffset++ @@ -2580,7 +2580,7 @@ func (tx *classFieldsTransformer) transformConstructorBody(container *ast.Node, } } statements = append(statements, initializerStatements...) - visited, _ := tx.Visitor().VisitSlice(body.Statements.Nodes[statementOffset:]) + visited, _ := tx.Visitor().VisitSlice(body.Statements().Nodes[statementOffset:]) statements = append(statements, visited...) } } else { @@ -2612,23 +2612,23 @@ func (tx *classFieldsTransformer) transformConstructorBody(container *ast.Node, } var multiLine bool - if constructor != nil && constructor.Body != nil && - len(constructor.Body.AsBlock().Statements.Nodes) >= len(statements) { - multiLine = constructor.Body.AsBlock().MultiLine + if constructor != nil && constructor.Body() != nil && + len(constructor.Body().AsBlock().Statements().Nodes) >= len(statements) { + multiLine = constructor.Body().AsBlock().MultiLine } else { multiLine = len(statements) > 0 } statementList := tx.Factory().NewNodeList(statements) - if constructor != nil && constructor.Body != nil { - statementList.Loc = constructor.Body.AsBlock().Statements.Loc + if constructor != nil && constructor.Body() != nil { + statementList.Loc = constructor.Body().AsBlock().Statements().Loc } else { statementList.Loc = core.NewTextRange(container.MemberList().Loc.Pos(), container.MemberList().Loc.End()) } block := tx.Factory().NewBlock(statementList, multiLine) - if constructor != nil && constructor.Body != nil { - block.Loc = constructor.Body.Loc + if constructor != nil && constructor.Body() != nil { + block.Loc = constructor.Body().Loc } return block } @@ -2756,14 +2756,14 @@ func (tx *classFieldsTransformer) transformPropertyWorker(property *ast.Property return createPrivateInstanceFieldInitializer( tx.Factory(), receiver, - tx.Visitor().VisitNode(property.Initializer), + tx.Visitor().VisitNode(property.Initializer()), info.brandCheckIdentifier, ) } return createPrivateStaticFieldInitializer( tx.Factory(), info.variableName, - tx.Visitor().VisitNode(property.Initializer), + tx.Visitor().VisitNode(property.Initializer()), ) } return nil @@ -2772,7 +2772,7 @@ func (tx *classFieldsTransformer) transformPropertyWorker(property *ast.Property } } - if (ast.IsPrivateIdentifier(propertyName) || ast.HasStaticModifier(property.AsNode())) && property.Initializer == nil { + if (ast.IsPrivateIdentifier(propertyName) || ast.HasStaticModifier(property.AsNode())) && property.Initializer() == nil { return nil } @@ -2781,9 +2781,9 @@ func (tx *classFieldsTransformer) transformPropertyWorker(property *ast.Property return nil } - initializer := tx.Visitor().VisitNode(property.Initializer) + initializer := tx.Visitor().VisitNode(property.Initializer()) propertyOriginalNode := tx.EmitContext().MostOriginal(property.AsNode()) - if ast.IsParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.Parent) && ast.IsIdentifier(propertyName) { //nolint:customlint // MostOriginal returns parse-tree nodes, and this parent relationship is intentional. + if ast.IsParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.Parent()) && ast.IsIdentifier(propertyName) { //nolint:customlint // MostOriginal returns parse-tree nodes, and this parent relationship is intentional. // A parameter-property declaration always overrides the initializer. The only time a parameter-property // declaration *should* have an initializer is when decorators have added initializers that need to run before // any other initializer @@ -2792,10 +2792,10 @@ func (tx *classFieldsTransformer) transformPropertyWorker(property *ast.Property // unwrap `(__runInitializers(this, _instanceExtraInitializers), void 0)` if ast.IsParenthesizedExpression(initializer) && ast.IsCommaExpression(initializer.Expression()) && - tx.EmitContext().IsCallToHelper(initializer.Expression().AsBinaryExpression().Left, "__runInitializers") && - ast.IsVoidExpression(initializer.Expression().AsBinaryExpression().Right) && - ast.IsNumericLiteral(initializer.Expression().AsBinaryExpression().Right.Expression()) { - initializer = initializer.Expression().AsBinaryExpression().Left + tx.EmitContext().IsCallToHelper(initializer.Expression().AsBinaryExpression().Left(), "__runInitializers") && + ast.IsVoidExpression(initializer.Expression().AsBinaryExpression().Right()) && + ast.IsNumericLiteral(initializer.Expression().AsBinaryExpression().Right().Expression()) { + initializer = initializer.Expression().AsBinaryExpression().Left() } initializer = tx.Factory().InlineExpressions([]*ast.Expression{initializer, localName}) } else { @@ -2864,7 +2864,7 @@ func (tx *classFieldsTransformer) visitInvalidSuperProperty(node *ast.Node) *ast node.AsElementAccessExpression(), tx.Factory().NewVoidZeroExpression(), nil, - tx.Visitor().VisitNode(node.AsElementAccessExpression().ArgumentExpression), + tx.Visitor().VisitNode(node.AsElementAccessExpression().ArgumentExpression()), node.Flags, ) } @@ -2891,7 +2891,7 @@ func (tx *classFieldsTransformer) getPropertyNameExpressionIfNeeded(name *ast.Pr tx.insideComputedPropertyName = savedInsideComputedPropertyName innerExpression := ast.SkipPartiallyEmittedExpressions(expression) inlinable := transformers.IsSimpleInlineableExpression(innerExpression) - alreadyTransformed := cacheAssignment != nil || (ast.IsAssignmentExpression(innerExpression, true /*excludeCompoundAssignment*/) && ast.IsIdentifier(innerExpression.AsBinaryExpression().Left) && transformers.IsGeneratedIdentifier(tx.EmitContext(), innerExpression.AsBinaryExpression().Left)) + alreadyTransformed := cacheAssignment != nil || (ast.IsAssignmentExpression(innerExpression, true /*excludeCompoundAssignment*/) && ast.IsIdentifier(innerExpression.AsBinaryExpression().Left()) && transformers.IsGeneratedIdentifier(tx.EmitContext(), innerExpression.AsBinaryExpression().Left())) if !alreadyTransformed && !inlinable && shouldHoist { generatedName := tx.Factory().NewGeneratedNameForNode(name) if tx.requiresBlockScopedVar() { @@ -3199,18 +3199,18 @@ func (tx *classFieldsTransformer) wrapPrivateIdentifierForDestructuringTarget(no if info == nil { return tx.Visitor().VisitEachChild(node) } - receiver := prop.Expression + receiver := prop.Expression() // We cannot copy `this` or `super` into the function because they will be bound // differently inside the function. - isThisOrSuperProperty := prop.Expression.Kind == ast.KindThisKeyword || prop.Expression.Kind == ast.KindSuperKeyword - if isThisOrSuperProperty || !transformers.IsSimpleCopiableExpression(prop.Expression) { + isThisOrSuperProperty := prop.Expression().Kind == ast.KindThisKeyword || prop.Expression().Kind == ast.KindSuperKeyword + if isThisOrSuperProperty || !transformers.IsSimpleCopiableExpression(prop.Expression()) { receiver = tx.Factory().NewTempVariableEx(printer.AutoGenerateOptions{ Flags: printer.GeneratedIdentifierFlagsReservedInNestedScopes, }) tx.EmitContext().AddVariableDeclaration(receiver) tx.pendingExpressions = append( tx.pendingExpressions, - tx.Factory().NewAssignmentExpression(receiver, tx.Visitor().VisitNode(prop.Expression)), + tx.Factory().NewAssignmentExpression(receiver, tx.Visitor().VisitNode(prop.Expression())), ) } assignExpr := tx.createPrivateIdentifierAssignment(info, receiver, parameter, ast.KindEqualsToken) @@ -3230,14 +3230,14 @@ func (tx *classFieldsTransformer) visitAssignmentElement(node *ast.Node) *ast.No node = transformNamedEvaluation(tx.EmitContext(), node, false /*ignoreEmptyStringLiteral*/, "" /*assignedName*/) } if ast.IsAssignmentExpression(node, true /*excludeCompoundAssignment*/) { - left := tx.visitDestructuringAssignmentTarget(node.AsBinaryExpression().Left) - right := tx.Visitor().VisitNode(node.AsBinaryExpression().Right) + left := tx.visitDestructuringAssignmentTarget(node.AsBinaryExpression().Left()) + right := tx.Visitor().VisitNode(node.AsBinaryExpression().Right()) return tx.Factory().UpdateBinaryExpression( node.AsBinaryExpression(), nil, left, nil, - node.AsBinaryExpression().OperatorToken, + node.AsBinaryExpression().OperatorToken(), right, ) } @@ -3246,8 +3246,8 @@ func (tx *classFieldsTransformer) visitAssignmentElement(node *ast.Node) *ast.No func (tx *classFieldsTransformer) visitAssignmentRestElement(node *ast.Node) *ast.Node { spread := node.AsSpreadElement() - if ast.IsLeftHandSideExpression(spread.Expression) { - expr := tx.visitDestructuringAssignmentTarget(spread.Expression) + if ast.IsLeftHandSideExpression(spread.Expression()) { + expr := tx.visitDestructuringAssignmentTarget(spread.Expression()) return tx.Factory().UpdateSpreadElement(spread, expr) } return tx.Visitor().VisitEachChild(node) @@ -3279,7 +3279,7 @@ func (tx *classFieldsTransformer) visitAssignmentProperty(node *ast.Node) *ast.N prop := node.AsPropertyAssignment() name := tx.Visitor().VisitNode(prop.Name()) - init := prop.Initializer + init := prop.Initializer() if ast.IsAssignmentExpression(init, true /*excludeCompoundAssignment*/) { assignElem := tx.visitAssignmentElement(init) return tx.Factory().UpdatePropertyAssignment(prop, nil, name, nil, nil, assignElem) @@ -3310,8 +3310,8 @@ func (tx *classFieldsTransformer) visitShorthandAssignmentProperty(node *ast.Nod func (tx *classFieldsTransformer) visitAssignmentRestProperty(node *ast.Node) *ast.Node { spread := node.AsSpreadAssignment() - if ast.IsLeftHandSideExpression(spread.Expression) { - expr := tx.visitDestructuringAssignmentTarget(spread.Expression) + if ast.IsLeftHandSideExpression(spread.Expression()) { + expr := tx.visitDestructuringAssignmentTarget(spread.Expression()) return tx.Factory().UpdateSpreadAssignment(spread, expr) } return tx.Visitor().VisitEachChild(node) @@ -3343,7 +3343,7 @@ func (tx *classFieldsTransformer) visitAssignmentPattern(node *ast.Node) *ast.No // [ { set value(x) { this.#myProp = x; } }.value ] = [ "hello" ]; return tx.Factory().UpdateArrayLiteralExpression( node.AsArrayLiteralExpression(), - tx.arrayAssignmentElementVisitor.VisitNodes(node.AsArrayLiteralExpression().Elements), + tx.arrayAssignmentElementVisitor.VisitNodes(node.AsArrayLiteralExpression().Elements()), node.AsArrayLiteralExpression().MultiLine, ) } @@ -3357,7 +3357,7 @@ func (tx *classFieldsTransformer) visitAssignmentPattern(node *ast.Node) *ast.No // ({ stringProperty: { set value(x) { this.#myProp = x; } }.value }) = { stringProperty: "hello" }; return tx.Factory().UpdateObjectLiteralExpression( node.AsObjectLiteralExpression(), - tx.objectAssignmentElementVisitor.VisitNodes(node.AsObjectLiteralExpression().Properties), + tx.objectAssignmentElementVisitor.VisitNodes(node.AsObjectLiteralExpression().Properties()), node.AsObjectLiteralExpression().MultiLine, ) } @@ -3460,12 +3460,12 @@ func (tx *classFieldsTransformer) createCallBinding(node *ast.Node) (thisArg *as } if ast.IsPropertyAccessExpression(node) { expr := node.AsPropertyAccessExpression() - if shouldBeCapturedInTempVariable(expr.Expression) { + if shouldBeCapturedInTempVariable(expr.Expression()) { thisArg = tx.Factory().NewTempVariable() tx.EmitContext().AddVariableDeclaration(thisArg) target = tx.Factory().NewPropertyAccessExpression( tx.Factory().NewParenthesizedExpression( // TODO: do we even need these? - tx.Factory().NewAssignmentExpression(thisArg, expr.Expression), + tx.Factory().NewAssignmentExpression(thisArg, expr.Expression()), ), nil, expr.Name(), @@ -3473,7 +3473,7 @@ func (tx *classFieldsTransformer) createCallBinding(node *ast.Node) (thisArg *as ) return thisArg, target } - return expr.Expression, node + return expr.Expression(), node } thisArg = tx.Factory().NewVoidZeroExpression() target = node @@ -3554,8 +3554,8 @@ func flattenCommaListWorker(node *ast.Expression, yield func(*ast.Expression) bo if ast.IsParenthesizedExpression(node) && ast.NodeIsSynthesized(node) { return flattenCommaListWorker(node.Expression(), yield) } else if ast.IsCommaExpression(node.AsNode()) { - return flattenCommaListWorker(node.AsBinaryExpression().Left, yield) && - flattenCommaListWorker(node.AsBinaryExpression().Right, yield) + return flattenCommaListWorker(node.AsBinaryExpression().Left(), yield) && + flattenCommaListWorker(node.AsBinaryExpression().Right(), yield) } else { return yield(node) } @@ -3565,11 +3565,11 @@ func findComputedPropertyNameCacheAssignment(emitContext *printer.EmitContext, n node := name.Expression() for { node = ast.SkipOuterExpressions(node, 0) - if ast.IsBinaryExpression(node) && node.AsBinaryExpression().OperatorToken.Kind == ast.KindCommaToken { - node = node.AsBinaryExpression().Right + if ast.IsBinaryExpression(node) && node.AsBinaryExpression().OperatorToken().Kind == ast.KindCommaToken { + node = node.AsBinaryExpression().Right() continue } - if ast.IsAssignmentExpression(node, true /*excludeCompoundAssignment*/) && ast.IsIdentifier(node.AsBinaryExpression().Left) { + if ast.IsAssignmentExpression(node, true /*excludeCompoundAssignment*/) && ast.IsIdentifier(node.AsBinaryExpression().Left()) { return node.AsBinaryExpression() } break @@ -3582,10 +3582,10 @@ func expandPreOrPostfixIncrementOrDecrementExpression(factory *printer.NodeFacto var operand *ast.Node if ast.IsPrefixUnaryExpression(node) { operator = node.AsPrefixUnaryExpression().Operator - operand = node.AsPrefixUnaryExpression().Operand + operand = node.AsPrefixUnaryExpression().Operand() } else { operator = node.AsPostfixUnaryExpression().Operator - operand = node.AsPostfixUnaryExpression().Operand + operand = node.AsPostfixUnaryExpression().Operand() } temp := factory.NewTempVariable() diff --git a/tsc/internal/transformers/estransforms/classthis.go b/tsc/internal/transformers/estransforms/classthis.go index 4ffe57644a8ce..fb4905cb023e9 100644 --- a/tsc/internal/transformers/estransforms/classthis.go +++ b/tsc/internal/transformers/estransforms/classthis.go @@ -10,16 +10,16 @@ import ( func isClassThisAssignmentBlock(emitContext *printer.EmitContext, node *ast.Node) bool { if ast.IsClassStaticBlockDeclaration(node) { n := node.AsClassStaticBlockDeclaration() - body := n.Body.AsBlock() - if len(body.Statements.Nodes) == 1 { - statement := body.Statements.Nodes[0] + body := n.Body().AsBlock() + if len(body.Statements().Nodes) == 1 { + statement := body.Statements().Nodes[0] if ast.IsExpressionStatement(statement) { expression := statement.Expression() if ast.IsAssignmentExpression(expression, true /*excludeCompoundAssignment*/) { binary := expression.AsBinaryExpression() - return ast.IsIdentifier(binary.Left) && - emitContext.ClassThis(node) == binary.Left && - binary.Right.Kind == ast.KindThisKeyword + return ast.IsIdentifier(binary.Left()) && + emitContext.ClassThis(node) == binary.Left() && + binary.Right().Kind == ast.KindThisKeyword } } } diff --git a/tsc/internal/transformers/estransforms/esdecorator.go b/tsc/internal/transformers/estransforms/esdecorator.go index dc2e6edee8a4d..25372990448fd 100644 --- a/tsc/internal/transformers/estransforms/esdecorator.go +++ b/tsc/internal/transformers/estransforms/esdecorator.go @@ -640,13 +640,13 @@ func (tx *esDecoratorTransformer) transformClassLike(node *ast.Node) *ast.Expres var extendsElement *ast.Node if extendsClause != nil { hc := extendsClause.AsHeritageClause() - if hc.Types != nil && len(hc.Types.Nodes) > 0 { - extendsElement = hc.Types.Nodes[0] + if hc.Types() != nil && len(hc.Types().Nodes) > 0 { + extendsElement = hc.Types().Nodes[0] } } var extendsExpression *ast.Expression if extendsElement != nil { - extendsExpression = tx.Visitor().VisitNode(extendsElement.AsExpressionWithTypeArguments().Expression) + extendsExpression = tx.Visitor().VisitNode(extendsElement.AsExpressionWithTypeArguments().Expression()) } if extendsExpression != nil { @@ -734,7 +734,7 @@ func (tx *esDecoratorTransformer) transformClassLike(node *ast.Node) *ast.Expres if len(ci.pendingInstanceInitializers) > 0 && ast.GetFirstConstructorWithBody(node) == nil { initializerStatements := tx.prepareConstructor(ci) if len(initializerStatements) > 0 { - isDerivedClass := extendsElement != nil && ast.SkipOuterExpressions(extendsElement.AsExpressionWithTypeArguments().Expression, ast.OEKAll).Kind != ast.KindNullKeyword + isDerivedClass := extendsElement != nil && ast.SkipOuterExpressions(extendsElement.AsExpressionWithTypeArguments().Expression(), ast.OEKAll).Kind != ast.KindNullKeyword constructorStatements := []*ast.Statement{} if isDerivedClass { spreadArguments := f.NewSpreadElement(f.NewIdentifier("arguments")) @@ -1097,9 +1097,9 @@ func (tx *esDecoratorTransformer) visitClassDeclaration(node *ast.ClassDeclarati // Non-decorated class modifiers := tx.modifierVisitor.VisitModifiers(node.Modifiers()) - heritageClauses := tx.Visitor().VisitNodes(node.HeritageClauses) + heritageClauses := tx.Visitor().VisitNodes(node.HeritageClauses()) tx.enterClass(nil) - members := tx.classElementVisitor.VisitNodes(node.Members) + members := tx.classElementVisitor.VisitNodes(node.Members()) tx.exitClass() return tx.Factory().UpdateClassDeclaration(node, modifiers, node.Name(), nil, heritageClauses, members) } @@ -1112,9 +1112,9 @@ func (tx *esDecoratorTransformer) visitClassExpression(node *ast.ClassExpression } modifiers := tx.modifierVisitor.VisitModifiers(node.Modifiers()) - heritageClauses := tx.Visitor().VisitNodes(node.HeritageClauses) + heritageClauses := tx.Visitor().VisitNodes(node.HeritageClauses()) tx.enterClass(nil) - members := tx.classElementVisitor.VisitNodes(node.Members) + members := tx.classElementVisitor.VisitNodes(node.Members()) tx.exitClass() return tx.Factory().UpdateClassExpression(node, modifiers, node.Name(), nil, heritageClauses, members) } @@ -1147,9 +1147,9 @@ func (tx *esDecoratorTransformer) transformConstructorBodyWorker(statementsOut [ superStatement := statementsIn[superStatementIndex] if ast.IsTryStatement(superStatement) { // Recurse into try block - tryBlockNode := superStatement.AsTryStatement().TryBlock + tryBlockNode := superStatement.AsTryStatement().TryBlock() tryBlock := tryBlockNode.AsBlock() - tryBlockStatements := tx.transformConstructorBodyWorker(nil, tryBlock.Statements.Nodes, 0, superPath, superPathDepth+1, initializerStatements) + tryBlockStatements := tx.transformConstructorBodyWorker(nil, tryBlock.Statements().Nodes, 0, superPath, superPathDepth+1, initializerStatements) newTryBlock := tx.Factory().NewBlock(tx.Factory().NewNodeList(tryBlockStatements), true) // Use the original try block's range even though the statements may differ due to @@ -1158,12 +1158,12 @@ func (tx *esDecoratorTransformer) transformConstructorBodyWorker(statementsOut [ newTryBlock.Loc = tryBlockNode.Loc var catchClause *ast.Node - if superStatement.AsTryStatement().CatchClause != nil { - catchClause = tx.Visitor().VisitNode(superStatement.AsTryStatement().CatchClause) + if superStatement.AsTryStatement().CatchClause() != nil { + catchClause = tx.Visitor().VisitNode(superStatement.AsTryStatement().CatchClause()) } var finallyBlock *ast.Node - if superStatement.AsTryStatement().FinallyBlock != nil { - finallyBlock = tx.Visitor().VisitNode(superStatement.AsTryStatement().FinallyBlock) + if superStatement.AsTryStatement().FinallyBlock() != nil { + finallyBlock = tx.Visitor().VisitNode(superStatement.AsTryStatement().FinallyBlock()) } updated := tx.Factory().UpdateTryStatement(superStatement.AsTryStatement(), newTryBlock, catchClause, finallyBlock) statementsOut = append(statementsOut, updated) @@ -1188,13 +1188,13 @@ func (tx *esDecoratorTransformer) visitConstructorDeclaration(node *ast.Node) *a var body *ast.Node ctor := node.AsConstructorDeclaration() - if ctor.Body != nil && tx.classInfoStack != nil { + if ctor.Body() != nil && tx.classInfoStack != nil { // If there are instance extra initializers we need to add them to the body along with any // field initializers initializerStatements := tx.prepareConstructor(tx.classInfoStack) if len(initializerStatements) > 0 { stmts := []*ast.Statement{} - prologue, rest := tx.Factory().SplitStandardPrologue(ctor.Body.AsBlock().Statements.Nodes) + prologue, rest := tx.Factory().SplitStandardPrologue(ctor.Body().AsBlock().Statements().Nodes) stmts = append(stmts, prologue...) superStatementIndices := transformers.FindSuperStatementIndexPath(rest, 0) @@ -1207,13 +1207,13 @@ func (tx *esDecoratorTransformer) visitConstructorDeclaration(node *ast.Node) *a } body = tx.Factory().NewBlock(tx.Factory().NewNodeList(stmts), true) - tx.EmitContext().SetOriginal(body, ctor.Body.AsNode()) - body.Loc = ctor.Body.Loc + tx.EmitContext().SetOriginal(body, ctor.Body().AsNode()) + body.Loc = ctor.Body().Loc } } if body == nil { - body = tx.Visitor().VisitNode(ctor.Body.AsNode()) + body = tx.Visitor().VisitNode(ctor.Body().AsNode()) } tx.exitClassElement() return tx.Factory().UpdateConstructorDeclaration(ctor, modifiers, nil, parameters, nil, nil, body) @@ -1312,9 +1312,9 @@ func (tx *esDecoratorTransformer) partialTransformClassElement(member *ast.Node, propertyNameExpr = f.NewStringLiteralFromNode(member.Name()) } else if member.Name() != nil && ast.IsComputedPropertyName(member.Name()) { cpn := member.Name().AsComputedPropertyName() - if ast.IsPropertyNameLiteral(cpn.Expression) && !ast.IsIdentifier(cpn.Expression) { + if ast.IsPropertyNameLiteral(cpn.Expression()) && !ast.IsIdentifier(cpn.Expression()) { propertyNameComputed = true - propertyNameExpr = f.NewStringLiteralFromNode(cpn.Expression) + propertyNameExpr = f.NewStringLiteralFromNode(cpn.Expression()) } else { tx.enterName() result.referencedName, result.name = tx.visitReferencedPropertyName(member.Name()) @@ -1474,7 +1474,7 @@ func (tx *esDecoratorTransformer) visitMethodDeclaration(node *ast.Node) *ast.No tx.exitClassElement() method := node.AsMethodDeclaration() return tx.finishClassElement( - tx.Factory().UpdateMethodDeclaration(method, result.modifiers, method.AsteriskToken, result.name, nil, nil, parameters, nil, nil, body), + tx.Factory().UpdateMethodDeclaration(method, result.modifiers, method.AsteriskToken(), result.name, nil, nil, parameters, nil, nil, body), node, ) } @@ -1539,10 +1539,10 @@ func (tx *esDecoratorTransformer) visitClassStaticBlockDeclaration(node *ast.Nod varStatements := ec.EndVariableEnvironment() if len(varStatements) > 0 { // Inject var declarations at the start of the static block's body - blockBody := result.AsClassStaticBlockDeclaration().Body.AsBlock() - newStmts := make([]*ast.Statement, 0, len(varStatements)+len(blockBody.Statements.Nodes)) + blockBody := result.AsClassStaticBlockDeclaration().Body().AsBlock() + newStmts := make([]*ast.Statement, 0, len(varStatements)+len(blockBody.Statements().Nodes)) newStmts = append(newStmts, varStatements...) - newStmts = append(newStmts, blockBody.Statements.Nodes...) + newStmts = append(newStmts, blockBody.Statements().Nodes...) result = f.NewClassStaticBlockDeclaration(nil, f.NewBlock(f.NewNodeList(newStmts), blockBody.MultiLine)) } if tx.classInfoStack != nil { @@ -1680,7 +1680,7 @@ func (tx *esDecoratorTransformer) visitPropertyDeclaration(node *ast.Node) *ast. cacheAssignment := findComputedPropertyNameCacheAssignment(ec, propName) if cacheAssignment != nil { getterName = f.UpdateComputedPropertyName(propName.AsComputedPropertyName(), tx.Visitor().VisitNode(propName.Expression())) - setterName = f.UpdateComputedPropertyName(propName.AsComputedPropertyName(), cacheAssignment.Left) + setterName = f.UpdateComputedPropertyName(propName.AsComputedPropertyName(), cacheAssignment.Left()) } else { temp := f.NewTempVariable() ec.SetSourceMapRange(temp, propName.Expression().Loc) @@ -1730,9 +1730,9 @@ func (tx *esDecoratorTransformer) visitThisExpression(node *ast.Node) *ast.Node func (tx *esDecoratorTransformer) visitCallExpression(node *ast.Node) *ast.Node { call := node.AsCallExpression() - if ast.IsSuperProperty(call.Expression) && tx.classThis != nil { - expression := tx.Visitor().VisitNode(call.Expression) - argumentsList := tx.Visitor().VisitNodes(call.Arguments) + if ast.IsSuperProperty(call.Expression()) && tx.classThis != nil { + expression := tx.Visitor().VisitNode(call.Expression()) + argumentsList := tx.Visitor().VisitNodes(call.Arguments()) invocation := tx.Factory().NewFunctionCallCall(expression, tx.classThis, argumentsList.Nodes) tx.EmitContext().SetOriginal(invocation, node) invocation.Loc = node.Loc @@ -1743,12 +1743,12 @@ func (tx *esDecoratorTransformer) visitCallExpression(node *ast.Node) *ast.Node func (tx *esDecoratorTransformer) visitTaggedTemplateExpression(node *ast.Node) *ast.Node { tte := node.AsTaggedTemplateExpression() - if ast.IsSuperProperty(tte.Tag) && tx.classThis != nil { - tag := tx.Visitor().VisitNode(tte.Tag) + if ast.IsSuperProperty(tte.Tag()) && tx.classThis != nil { + tag := tx.Visitor().VisitNode(tte.Tag()) boundTag := tx.Factory().NewFunctionBindCall(tag, tx.classThis, []*ast.Expression{}) tx.EmitContext().SetOriginal(boundTag, node) boundTag.Loc = node.Loc - template := tx.Visitor().VisitNode(tte.Template) + template := tx.Visitor().VisitNode(tte.Template()) return tx.Factory().UpdateTaggedTemplateExpression(tte, boundTag, nil, nil, template, tte.Flags) } return tx.Visitor().VisitEachChild(node) @@ -1759,8 +1759,8 @@ func (tx *esDecoratorTransformer) visitPropertyAccessExpression(node *ast.Node) if ast.IsSuperProperty(node) && ast.IsIdentifier(pa.Name()) && tx.classThis != nil && tx.classSuper != nil { propertyName := tx.Factory().NewStringLiteralFromNode(pa.Name()) superProperty := tx.Factory().NewReflectGetCall(tx.classSuper, propertyName, tx.classThis) - tx.EmitContext().SetOriginal(superProperty, pa.Expression) - superProperty.Loc = pa.Expression.Loc + tx.EmitContext().SetOriginal(superProperty, pa.Expression()) + superProperty.Loc = pa.Expression().Loc return superProperty } return tx.Visitor().VisitEachChild(node) @@ -1769,10 +1769,10 @@ func (tx *esDecoratorTransformer) visitPropertyAccessExpression(node *ast.Node) func (tx *esDecoratorTransformer) visitElementAccessExpression(node *ast.Node) *ast.Node { ea := node.AsElementAccessExpression() if ast.IsSuperProperty(node) && tx.classThis != nil && tx.classSuper != nil { - propertyName := tx.Visitor().VisitNode(ea.ArgumentExpression) + propertyName := tx.Visitor().VisitNode(ea.ArgumentExpression()) superProperty := tx.Factory().NewReflectGetCall(tx.classSuper, propertyName, tx.classThis) - tx.EmitContext().SetOriginal(superProperty, ea.Expression) - superProperty.Loc = ea.Expression.Loc + tx.EmitContext().SetOriginal(superProperty, ea.Expression()) + superProperty.Loc = ea.Expression().Loc return superProperty } return tx.Visitor().VisitEachChild(node) @@ -1805,11 +1805,11 @@ func (tx *esDecoratorTransformer) visitParameterDeclaration(node *ast.ParameterD updated := tx.Factory().UpdateParameterDeclaration( node, nil, // modifiers - strip all modifiers (including decorators) - node.DotDotDotToken, + node.DotDotDotToken(), tx.Visitor().VisitNode(node.Name()), nil, // questionToken nil, // type - tx.Visitor().VisitNode(node.Initializer), + tx.Visitor().VisitNode(node.Initializer()), ) if updated != paramNode { // While we emit the source map for the node after skipping decorators and modifiers, @@ -1895,10 +1895,10 @@ func (tx *esDecoratorTransformer) visitForStatement(node *ast.Node) *ast.Node { forStmt := node.AsForStatement() return f.UpdateForStatement( forStmt, - tx.discardedVisitor.VisitNode(forStmt.Initializer), - tx.Visitor().VisitNode(forStmt.Condition), - tx.discardedVisitor.VisitNode(forStmt.Incrementor), - tx.EmitContext().VisitIterationBody(forStmt.Statement, tx.Visitor()), + tx.discardedVisitor.VisitNode(forStmt.Initializer()), + tx.Visitor().VisitNode(forStmt.Condition()), + tx.discardedVisitor.VisitNode(forStmt.Incrementor()), + tx.EmitContext().VisitIterationBody(forStmt.Statement(), tx.Visitor()), ) } @@ -1912,9 +1912,9 @@ func (tx *esDecoratorTransformer) visitBinaryExpression(node *ast.Node, discarde bin := node.AsBinaryExpression() if ast.IsDestructuringAssignment(node) { - left := tx.visitAssignmentPattern(bin.Left) - right := tx.Visitor().VisitNode(bin.Right) - return f.UpdateBinaryExpression(bin, nil, left, nil, bin.OperatorToken, right) + left := tx.visitAssignmentPattern(bin.Left()) + right := tx.Visitor().VisitNode(bin.Right()) + return f.UpdateBinaryExpression(bin, nil, left, nil, bin.OperatorToken(), right) } if ast.IsAssignmentExpression(node, false) { @@ -1945,24 +1945,24 @@ func (tx *esDecoratorTransformer) visitBinaryExpression(node *ast.Node, discarde // ... if isNamedEvaluationAnd(ec, node, isAnonymousClassNeedingAssignedName) { - node = transformNamedEvaluation(ec, node, canIgnoreEmptyStringLiteralInAssignedName(bin.Right), "") + node = transformNamedEvaluation(ec, node, canIgnoreEmptyStringLiteralInAssignedName(bin.Right()), "") return tx.Visitor().VisitEachChild(node) } - if ast.IsSuperProperty(bin.Left) && tx.classThis != nil && tx.classSuper != nil { + if ast.IsSuperProperty(bin.Left()) && tx.classThis != nil && tx.classSuper != nil { var setterName *ast.Expression - if ast.IsElementAccessExpression(bin.Left) { - setterName = tx.Visitor().VisitNode(bin.Left.AsElementAccessExpression().ArgumentExpression) - } else if ast.IsPropertyAccessExpression(bin.Left) && ast.IsIdentifier(bin.Left.AsPropertyAccessExpression().Name()) { - setterName = f.NewStringLiteralFromNode(bin.Left.AsPropertyAccessExpression().Name()) + if ast.IsElementAccessExpression(bin.Left()) { + setterName = tx.Visitor().VisitNode(bin.Left().AsElementAccessExpression().ArgumentExpression()) + } else if ast.IsPropertyAccessExpression(bin.Left()) && ast.IsIdentifier(bin.Left().AsPropertyAccessExpression().Name()) { + setterName = f.NewStringLiteralFromNode(bin.Left().AsPropertyAccessExpression().Name()) } if setterName != nil { // super.x = ... // super.x += ... // super[x] = ... // super[x] += ... - expression := tx.Visitor().VisitNode(bin.Right) - if ast.IsCompoundAssignment(bin.OperatorToken.Kind) { + expression := tx.Visitor().VisitNode(bin.Right()) + if ast.IsCompoundAssignment(bin.OperatorToken().Kind) { getterName := setterName if !transformers.IsSimpleInlineableExpression(setterName) { getterName = f.NewTempVariable() @@ -1970,13 +1970,13 @@ func (tx *esDecoratorTransformer) visitBinaryExpression(node *ast.Node, discarde setterName = f.NewAssignmentExpression(getterName, setterName) } superPropertyGet := f.NewReflectGetCall(tx.classSuper, getterName, tx.classThis) - ec.SetOriginal(superPropertyGet, bin.Left) - superPropertyGet.Loc = bin.Left.Loc + ec.SetOriginal(superPropertyGet, bin.Left()) + superPropertyGet.Loc = bin.Left().Loc expression = f.AsNodeFactory().NewBinaryExpression( nil, superPropertyGet, nil, - f.NewToken(transformers.GetNonAssignmentOperatorForCompoundAssignment(bin.OperatorToken.Kind)), + f.NewToken(transformers.GetNonAssignmentOperatorForCompoundAssignment(bin.OperatorToken().Kind)), expression, ) expression.Loc = node.Loc @@ -2002,15 +2002,15 @@ func (tx *esDecoratorTransformer) visitBinaryExpression(node *ast.Node, discarde } } - if bin.OperatorToken.Kind == ast.KindCommaToken { - left := tx.discardedVisitor.VisitNode(bin.Left) + if bin.OperatorToken().Kind == ast.KindCommaToken { + left := tx.discardedVisitor.VisitNode(bin.Left()) var right *ast.Node if discarded { - right = tx.discardedVisitor.VisitNode(bin.Right) + right = tx.discardedVisitor.VisitNode(bin.Right()) } else { - right = tx.Visitor().VisitNode(bin.Right) + right = tx.Visitor().VisitNode(bin.Right()) } - return f.UpdateBinaryExpression(bin, nil, left, nil, bin.OperatorToken, right) + return f.UpdateBinaryExpression(bin, nil, left, nil, bin.OperatorToken(), right) } return tx.Visitor().VisitEachChild(node) @@ -2024,10 +2024,10 @@ func (tx *esDecoratorTransformer) visitPreOrPostfixUnaryExpression(node *ast.Nod var operandNode *ast.Node if ast.IsPrefixUnaryExpression(node) { operator = node.AsPrefixUnaryExpression().Operator - operandNode = node.AsPrefixUnaryExpression().Operand + operandNode = node.AsPrefixUnaryExpression().Operand() } else { operator = node.AsPostfixUnaryExpression().Operator - operandNode = node.AsPostfixUnaryExpression().Operand + operandNode = node.AsPostfixUnaryExpression().Operand() } if operator == ast.KindPlusPlusToken || operator == ast.KindMinusMinusToken { @@ -2035,7 +2035,7 @@ func (tx *esDecoratorTransformer) visitPreOrPostfixUnaryExpression(node *ast.Nod if ast.IsSuperProperty(operand) && tx.classThis != nil && tx.classSuper != nil { var setterName *ast.Expression if ast.IsElementAccessExpression(operand) { - setterName = tx.Visitor().VisitNode(operand.AsElementAccessExpression().ArgumentExpression) + setterName = tx.Visitor().VisitNode(operand.AsElementAccessExpression().ArgumentExpression()) } else if ast.IsPropertyAccessExpression(operand) && ast.IsIdentifier(operand.AsPropertyAccessExpression().Name()) { setterName = f.NewStringLiteralFromNode(operand.AsPropertyAccessExpression().Name()) } @@ -2102,14 +2102,14 @@ func (tx *esDecoratorTransformer) visitReferencedPropertyName(node *ast.Node) (* } cpn := node.AsComputedPropertyName() - if ast.IsPropertyNameLiteral(cpn.Expression) && !ast.IsIdentifier(cpn.Expression) { - return tx.Factory().NewStringLiteralFromNode(cpn.Expression), tx.Visitor().VisitNode(node) + if ast.IsPropertyNameLiteral(cpn.Expression()) && !ast.IsIdentifier(cpn.Expression()) { + return tx.Factory().NewStringLiteralFromNode(cpn.Expression()), tx.Visitor().VisitNode(node) } referencedName := tx.Factory().NewGeneratedNameForNode(node) tx.EmitContext().AddVariableDeclaration(referencedName) - key := tx.Factory().NewPropKeyHelper(tx.Visitor().VisitNode(cpn.Expression)) + key := tx.Factory().NewPropKeyHelper(tx.Visitor().VisitNode(cpn.Expression())) assignment := tx.Factory().NewAssignmentExpression(referencedName, key) updatedName := tx.Factory().UpdateComputedPropertyName(cpn, tx.injectPendingExpressions(assignment)) return referencedName, updatedName @@ -2124,7 +2124,7 @@ func (tx *esDecoratorTransformer) visitPropertyName(node *ast.Node) *ast.Node { func (tx *esDecoratorTransformer) visitComputedPropertyName(node *ast.Node) *ast.Node { cpn := node.AsComputedPropertyName() - expression := tx.Visitor().VisitNode(cpn.Expression) + expression := tx.Visitor().VisitNode(cpn.Expression()) if !transformers.IsSimpleInlineableExpression(expression) { expression = tx.injectPendingExpressions(expression) } @@ -2141,7 +2141,7 @@ func (tx *esDecoratorTransformer) visitDestructuringAssignmentTarget(node *ast.N ec := tx.EmitContext() var propertyName *ast.Expression if ast.IsElementAccessExpression(node) { - propertyName = tx.Visitor().VisitNode(node.AsElementAccessExpression().ArgumentExpression) + propertyName = tx.Visitor().VisitNode(node.AsElementAccessExpression().ArgumentExpression()) } else if ast.IsPropertyAccessExpression(node) && ast.IsIdentifier(node.AsPropertyAccessExpression().Name()) { propertyName = f.NewStringLiteralFromNode(node.AsPropertyAccessExpression().Name()) } @@ -2177,21 +2177,21 @@ func (tx *esDecoratorTransformer) visitAssignmentElement(node *ast.Node) *ast.No f := tx.Factory() bin := node.AsBinaryExpression() if isNamedEvaluationAnd(tx.EmitContext(), node, isAnonymousClassNeedingAssignedName) { - node = transformNamedEvaluation(tx.EmitContext(), node, canIgnoreEmptyStringLiteralInAssignedName(bin.Right), "") + node = transformNamedEvaluation(tx.EmitContext(), node, canIgnoreEmptyStringLiteralInAssignedName(bin.Right()), "") bin = node.AsBinaryExpression() } - assignmentTarget := tx.visitDestructuringAssignmentTarget(bin.Left) - initializer := tx.Visitor().VisitNode(bin.Right) - return f.UpdateBinaryExpression(bin, nil, assignmentTarget, nil, bin.OperatorToken, initializer) + assignmentTarget := tx.visitDestructuringAssignmentTarget(bin.Left()) + initializer := tx.Visitor().VisitNode(bin.Right()) + return f.UpdateBinaryExpression(bin, nil, assignmentTarget, nil, bin.OperatorToken(), initializer) } return tx.visitDestructuringAssignmentTarget(node) } func (tx *esDecoratorTransformer) visitAssignmentRestElement(node *ast.Node) *ast.Node { se := node.AsSpreadElement() - if ast.IsLeftHandSideExpression(se.Expression) { + if ast.IsLeftHandSideExpression(se.Expression()) { f := tx.Factory() - expression := tx.visitDestructuringAssignmentTarget(se.Expression) + expression := tx.visitDestructuringAssignmentTarget(se.Expression()) return f.UpdateSpreadElement(se, expression) } return tx.Visitor().VisitEachChild(node) @@ -2223,12 +2223,12 @@ func (tx *esDecoratorTransformer) visitAssignmentPropertyNode(node *ast.Node) *a f := tx.Factory() pa := node.AsPropertyAssignment() name := tx.Visitor().VisitNode(pa.Name()) - if ast.IsAssignmentExpression(pa.Initializer, true /*excludeCompoundAssignment*/) { - assignmentElement := tx.visitAssignmentElement(pa.Initializer) + if ast.IsAssignmentExpression(pa.Initializer(), true /*excludeCompoundAssignment*/) { + assignmentElement := tx.visitAssignmentElement(pa.Initializer()) return f.UpdatePropertyAssignment(pa, nil, name, nil, nil, assignmentElement) } - if ast.IsLeftHandSideExpression(pa.Initializer) { - assignmentElement := tx.visitDestructuringAssignmentTarget(pa.Initializer) + if ast.IsLeftHandSideExpression(pa.Initializer()) { + assignmentElement := tx.visitDestructuringAssignmentTarget(pa.Initializer()) return f.UpdatePropertyAssignment(pa, nil, name, nil, nil, assignmentElement) } return tx.Visitor().VisitEachChild(node) @@ -2245,16 +2245,16 @@ func (tx *esDecoratorTransformer) visitShorthandAssignmentProperty(node *ast.Nod // i. Set _v_ to ? NamedEvaluation of |Initializer| with argument _P_. // ... if isNamedEvaluationAnd(tx.EmitContext(), node, isAnonymousClassNeedingAssignedName) { - node = transformNamedEvaluation(tx.EmitContext(), node, canIgnoreEmptyStringLiteralInAssignedName(node.AsShorthandPropertyAssignment().ObjectAssignmentInitializer), "") + node = transformNamedEvaluation(tx.EmitContext(), node, canIgnoreEmptyStringLiteralInAssignedName(node.AsShorthandPropertyAssignment().ObjectAssignmentInitializer()), "") } return tx.Visitor().VisitEachChild(node) } func (tx *esDecoratorTransformer) visitAssignmentRestProperty(node *ast.Node) *ast.Node { sa := node.AsSpreadAssignment() - if ast.IsLeftHandSideExpression(sa.Expression) { + if ast.IsLeftHandSideExpression(sa.Expression()) { f := tx.Factory() - expression := tx.visitDestructuringAssignmentTarget(sa.Expression) + expression := tx.visitDestructuringAssignmentTarget(sa.Expression()) return f.UpdateSpreadAssignment(sa, expression) } return tx.Visitor().VisitEachChild(node) @@ -2278,11 +2278,11 @@ func (tx *esDecoratorTransformer) visitAssignmentPattern(node *ast.Node) *ast.No f := tx.Factory() if ast.IsArrayLiteralExpression(node) { ale := node.AsArrayLiteralExpression() - elements := tx.arrayAssignmentVisitor.VisitNodes(ale.Elements) + elements := tx.arrayAssignmentVisitor.VisitNodes(ale.Elements()) return f.UpdateArrayLiteralExpression(ale, elements, ale.MultiLine) } ole := node.AsObjectLiteralExpression() - properties := tx.objectAssignmentVisitor.VisitNodes(ole.Properties) + properties := tx.objectAssignmentVisitor.VisitNodes(ole.Properties()) return f.UpdateObjectLiteralExpression(ole, properties, ole.MultiLine) } @@ -2305,9 +2305,9 @@ func (tx *esDecoratorTransformer) visitParenthesizedExpression(node *ast.Node, d pe := node.AsParenthesizedExpression() var expression *ast.Node if discarded { - expression = tx.discardedVisitor.VisitNode(pe.Expression) + expression = tx.discardedVisitor.VisitNode(pe.Expression()) } else { - expression = tx.Visitor().VisitNode(pe.Expression) + expression = tx.Visitor().VisitNode(pe.Expression()) } return f.UpdateParenthesizedExpression(pe, expression) } @@ -2317,9 +2317,9 @@ func (tx *esDecoratorTransformer) visitPartiallyEmittedExpression(node *ast.Node pe := node.AsPartiallyEmittedExpression() var expression *ast.Node if discarded { - expression = tx.discardedVisitor.VisitNode(pe.Expression) + expression = tx.discardedVisitor.VisitNode(pe.Expression()) } else { - expression = tx.Visitor().VisitNode(pe.Expression) + expression = tx.Visitor().VisitNode(pe.Expression()) } return tx.Factory().UpdatePartiallyEmittedExpression(pe, expression) } @@ -2338,7 +2338,7 @@ func (tx *esDecoratorTransformer) prependExpressions(pending []*ast.Expression, pe := expression.AsParenthesizedExpression() exprs := make([]*ast.Expression, len(pending)+1) copy(exprs, pending) - exprs[len(pending)] = pe.Expression + exprs[len(pending)] = pe.Expression() return f.UpdateParenthesizedExpression(pe, f.InlineExpressions(exprs)) } exprs := make([]*ast.Expression, len(pending)+1) @@ -2384,7 +2384,7 @@ func (tx *esDecoratorTransformer) transformAllDecoratorsOfDeclaration(decorators // Transforms a decorator into an expression. func (tx *esDecoratorTransformer) transformDecorator(decorator *ast.Node) *ast.Expression { - expression := tx.Visitor().VisitNode(decorator.AsDecorator().Expression) + expression := tx.Visitor().VisitNode(decorator.AsDecorator().Expression()) tx.EmitContext().SetEmitFlags(expression, printer.EFNoComments) // preserve the 'this' binding for an access expression @@ -2411,29 +2411,29 @@ func (tx *esDecoratorTransformer) createCallBinding(expression *ast.Expression) } if ast.IsPropertyAccessExpression(callee) { pa := callee.AsPropertyAccessExpression() - if tx.shouldBeCapturedInTempVariable(pa.Expression) { + if tx.shouldBeCapturedInTempVariable(pa.Expression()) { thisArg := f.NewTempVariable() tx.EmitContext().AddVariableDeclaration(thisArg) - assign := f.NewAssignmentExpression(thisArg, pa.Expression) - assign.Loc = pa.Expression.Loc + assign := f.NewAssignmentExpression(thisArg, pa.Expression()) + assign.Loc = pa.Expression().Loc target := f.NewPropertyAccessExpression(assign, nil, pa.Name(), ast.NodeFlagsNone) target.Loc = callee.Loc return target, thisArg } - return callee, pa.Expression + return callee, pa.Expression() } if ast.IsElementAccessExpression(callee) { ea := callee.AsElementAccessExpression() - if tx.shouldBeCapturedInTempVariable(ea.Expression) { + if tx.shouldBeCapturedInTempVariable(ea.Expression()) { thisArg := f.NewTempVariable() tx.EmitContext().AddVariableDeclaration(thisArg) - assign := f.NewAssignmentExpression(thisArg, ea.Expression) - assign.Loc = ea.Expression.Loc - target := f.NewElementAccessExpression(assign, nil, ea.ArgumentExpression, ast.NodeFlagsNone) + assign := f.NewAssignmentExpression(thisArg, ea.Expression()) + assign.Loc = ea.Expression().Loc + target := f.NewElementAccessExpression(assign, nil, ea.ArgumentExpression(), ast.NodeFlagsNone) target.Loc = callee.Loc return target, thisArg } - return callee, ea.Expression + return callee, ea.Expression() } return expression, f.NewVoidZeroExpression() } @@ -2511,7 +2511,7 @@ func (tx *esDecoratorTransformer) createMethodDescriptorObject(member *ast.Node, method := member.AsMethodDeclaration() return f.NewObjectLiteralExpression( f.NewNodeList([]*ast.Node{ - tx.createDescriptorMethod(member, member.Name(), modifiers, method.AsteriskToken, "value", parameters, body), + tx.createDescriptorMethod(member, member.Name(), modifiers, method.AsteriskToken(), "value", parameters, body), }), false, ) @@ -2741,10 +2741,10 @@ func injectClassThisAssignmentIfMissing(ec *printer.EmitContext, f *printer.Node var updatedNode *ast.Node if ast.IsClassDeclaration(node) { cd := node.AsClassDeclaration() - updatedNode = f.UpdateClassDeclaration(cd, cd.Modifiers(), cd.Name(), nil, cd.HeritageClauses, membersList) + updatedNode = f.UpdateClassDeclaration(cd, cd.Modifiers(), cd.Name(), nil, cd.HeritageClauses(), membersList) } else { ce := node.AsClassExpression() - updatedNode = f.UpdateClassExpression(ce, ce.Modifiers(), ce.Name(), nil, ce.HeritageClauses, membersList) + updatedNode = f.UpdateClassExpression(ce, ce.Modifiers(), ce.Name(), nil, ce.HeritageClauses(), membersList) } ec.SetClassThis(updatedNode, classThis) return updatedNode diff --git a/tsc/internal/transformers/estransforms/exponentiation.go b/tsc/internal/transformers/estransforms/exponentiation.go index c1cf0c5a0b7c8..cec60c6e55ba6 100644 --- a/tsc/internal/transformers/estransforms/exponentiation.go +++ b/tsc/internal/transformers/estransforms/exponentiation.go @@ -22,7 +22,7 @@ func (ch *exponentiationTransformer) visit(node *ast.Node) *ast.Node { } func (ch *exponentiationTransformer) visitBinaryExpression(node *ast.BinaryExpression) *ast.Node { - switch node.OperatorToken.Kind { + switch node.OperatorToken().Kind { case ast.KindAsteriskAsteriskEqualsToken: return ch.visitExponentiationAssignmentExpression(node) case ast.KindAsteriskAsteriskToken: @@ -34,8 +34,8 @@ func (ch *exponentiationTransformer) visitBinaryExpression(node *ast.BinaryExpre func (ch *exponentiationTransformer) visitExponentiationAssignmentExpression(node *ast.BinaryExpression) *ast.Node { var target *ast.Node var value *ast.Node - left := ch.Visitor().VisitNode(node.Left) - right := ch.Visitor().VisitNode(node.Right) + left := ch.Visitor().VisitNode(node.Left()) + right := ch.Visitor().VisitNode(node.Right()) if ast.IsElementAccessExpression(left) { // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)` expressionTemp := ch.Factory().NewTempVariable() @@ -45,8 +45,8 @@ func (ch *exponentiationTransformer) visitExponentiationAssignmentExpression(nod objExpr := ch.Factory().NewAssignmentExpression(expressionTemp, left.Expression()) objExpr.Loc = left.Expression().Loc - accessExpr := ch.Factory().NewAssignmentExpression(argumentExpressionTemp, left.AsElementAccessExpression().ArgumentExpression) - accessExpr.Loc = left.AsElementAccessExpression().ArgumentExpression.Loc + accessExpr := ch.Factory().NewAssignmentExpression(argumentExpressionTemp, left.AsElementAccessExpression().ArgumentExpression()) + accessExpr.Loc = left.AsElementAccessExpression().ArgumentExpression().Loc target = ch.Factory().NewElementAccessExpression(objExpr, nil, accessExpr, ast.NodeFlagsNone) @@ -77,8 +77,8 @@ func (ch *exponentiationTransformer) visitExponentiationAssignmentExpression(nod } func (ch *exponentiationTransformer) visitExponentiationExpression(node *ast.BinaryExpression) *ast.Node { - left := ch.Visitor().VisitNode(node.Left) - right := ch.Visitor().VisitNode(node.Right) + left := ch.Visitor().VisitNode(node.Left()) + right := ch.Visitor().VisitNode(node.Right()) result := ch.Factory().NewGlobalMethodCall("Math", "pow", []*ast.Node{left, right}) result.Loc = node.Loc return result diff --git a/tsc/internal/transformers/estransforms/forawait.go b/tsc/internal/transformers/estransforms/forawait.go index 4d2ddafb13b77..c31ba3a360828 100644 --- a/tsc/internal/transformers/estransforms/forawait.go +++ b/tsc/internal/transformers/estransforms/forawait.go @@ -220,7 +220,7 @@ func (tx *forawaitTransformer) visitAwaitExpression(node *ast.AwaitExpression) * if tx.enclosingFunctionFlags&ast.FunctionFlagsAsync != 0 && tx.enclosingFunctionFlags&ast.FunctionFlagsGenerator != 0 { result := tx.Factory().NewYieldExpression( nil, /*asteriskToken*/ - tx.Factory().NewAwaitHelper(tx.Visitor().VisitNode(node.Expression)), + tx.Factory().NewAwaitHelper(tx.Visitor().VisitNode(node.Expression())), ) result.Loc = node.Loc tx.EmitContext().SetOriginal(result, node.AsNode()) @@ -231,8 +231,8 @@ func (tx *forawaitTransformer) visitAwaitExpression(node *ast.AwaitExpression) * func (tx *forawaitTransformer) visitYieldExpression(node *ast.YieldExpression) *ast.Node { if tx.enclosingFunctionFlags&ast.FunctionFlagsAsync != 0 && tx.enclosingFunctionFlags&ast.FunctionFlagsGenerator != 0 { - if node.AsteriskToken != nil { - expression := tx.Visitor().VisitNode(node.Expression) + if node.AsteriskToken() != nil { + expression := tx.Visitor().VisitNode(node.Expression()) asyncValuesResult := tx.Factory().NewAsyncValuesHelper(expression) asyncValuesResult.Loc = expression.Loc @@ -242,7 +242,7 @@ func (tx *forawaitTransformer) visitYieldExpression(node *ast.YieldExpression) * innerYield := tx.Factory().UpdateYieldExpression( node, - node.AsteriskToken, + node.AsteriskToken(), asyncDelegatorResult, ) @@ -258,8 +258,8 @@ func (tx *forawaitTransformer) visitYieldExpression(node *ast.YieldExpression) * } var innerExpression *ast.Node - if node.Expression != nil { - innerExpression = tx.Visitor().VisitNode(node.Expression) + if node.Expression() != nil { + innerExpression = tx.Visitor().VisitNode(node.Expression()) } else { innerExpression = tx.Factory().NewVoidZeroExpression() } @@ -279,8 +279,8 @@ func (tx *forawaitTransformer) visitYieldExpression(node *ast.YieldExpression) * func (tx *forawaitTransformer) visitReturnStatement(node *ast.ReturnStatement) *ast.Node { if tx.enclosingFunctionFlags&ast.FunctionFlagsAsync != 0 && tx.enclosingFunctionFlags&ast.FunctionFlagsGenerator != 0 { var expression *ast.Node - if node.Expression != nil { - expression = tx.Visitor().VisitNode(node.Expression) + if node.Expression() != nil { + expression = tx.Visitor().VisitNode(node.Expression()) } else { expression = tx.Factory().NewVoidZeroExpression() } @@ -296,7 +296,7 @@ func (tx *forawaitTransformer) visitReturnStatement(node *ast.ReturnStatement) * func (tx *forawaitTransformer) visitLabeledStatement(node *ast.LabeledStatement) *ast.Node { if tx.enclosingFunctionFlags&ast.FunctionFlagsAsync != 0 { statement := unwrapInnermostStatementOfLabel(node) - if statement.Kind == ast.KindForOfStatement && statement.AsForInOrOfStatement().AwaitModifier != nil { + if statement.Kind == ast.KindForOfStatement && statement.AsForInOrOfStatement().AwaitModifier() != nil { return tx.visitForOfStatement(statement.AsForInOrOfStatement(), node) } return tx.Factory().RestoreEnclosingLabel(tx.Visitor().VisitNode(statement), node) @@ -307,10 +307,10 @@ func (tx *forawaitTransformer) visitLabeledStatement(node *ast.LabeledStatement) // unwrapInnermostStatementOfLabel follows LabeledStatement chains to find the innermost statement. func unwrapInnermostStatementOfLabel(node *ast.LabeledStatement) *ast.Node { for { - if node.Statement.Kind != ast.KindLabeledStatement { - return node.Statement + if node.Statement().Kind != ast.KindLabeledStatement { + return node.Statement() } - node = node.Statement.AsLabeledStatement() + node = node.Statement().AsLabeledStatement() } } @@ -330,7 +330,7 @@ func (tx *forawaitTransformer) visitSourceFile(node *ast.SourceFile) *ast.Node { func (tx *forawaitTransformer) visitForOfStatement(node *ast.ForInOrOfStatement, outermostLabeledStatement *ast.LabeledStatement) *ast.Node { ancestorFacts := tx.enterSubtree(forAwaitHierarchyFactsIterationStatementExcludes, forAwaitHierarchyFactsIterationStatementIncludes) var result *ast.Node - if node.AwaitModifier != nil { + if node.AwaitModifier() != nil { result = tx.transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) } else { result = tx.Factory().RestoreEnclosingLabel(tx.Visitor().VisitEachChild(node.AsNode()), outermostLabeledStatement) @@ -345,19 +345,19 @@ func (tx *forawaitTransformer) convertForOfStatementHead(node *ast.ForInOrOfStat tx.EmitContext().AddVariableDeclaration(value) iteratorValueExpression := f.NewAssignmentExpression(value, boundValue) iteratorValueStatement := f.NewExpressionStatement(iteratorValueExpression) - tx.EmitContext().SetSourceMapRange(iteratorValueStatement, node.Expression.Loc) + tx.EmitContext().SetSourceMapRange(iteratorValueStatement, node.Expression().Loc) exitNonUserCodeExpression := f.NewAssignmentExpression(nonUserCode, f.NewKeywordExpression(ast.KindFalseKeyword)) exitNonUserCodeStatement := f.NewExpressionStatement(exitNonUserCodeExpression) - tx.EmitContext().SetSourceMapRange(exitNonUserCodeStatement, node.Expression.Loc) + tx.EmitContext().SetSourceMapRange(exitNonUserCodeStatement, node.Expression().Loc) statements := []*ast.Node{iteratorValueStatement, exitNonUserCodeStatement} - binding := tx.Factory().CreateForOfBindingStatement(node.Initializer, value) + binding := tx.Factory().CreateForOfBindingStatement(node.Initializer(), value) statements = append(statements, tx.Visitor().VisitNode(binding)) var bodyLocation core.TextRange var statementsLocation core.TextRange - statement := tx.Visitor().VisitEmbeddedStatement(node.Statement) + statement := tx.Visitor().VisitEmbeddedStatement(node.Statement()) if ast.IsBlock(statement) { statements = append(statements, statement.Statements()...) bodyLocation = statement.Loc @@ -385,7 +385,7 @@ func (tx *forawaitTransformer) createDownlevelAwait(expression *ast.Node) *ast.N func (tx *forawaitTransformer) transformForAwaitOfStatement(node *ast.ForInOrOfStatement, outermostLabeledStatement *ast.LabeledStatement, ancestorFacts forAwaitHierarchyFacts) *ast.Node { f := tx.Factory() - expression := tx.Visitor().VisitNode(node.Expression) + expression := tx.Visitor().VisitNode(node.Expression()) var iterator *ast.Node if ast.IsIdentifier(expression) { @@ -408,7 +408,7 @@ func (tx *forawaitTransformer) transformForAwaitOfStatement(node *ast.ForInOrOfS catchVariable := f.NewGeneratedNameForNode(errorRecord) returnMethod := f.NewTempVariable() callValues := f.NewAsyncValuesHelper(expression) - callValues.Loc = node.Expression.Loc + callValues.Loc = node.Expression().Loc callNext := f.NewCallExpression( f.NewPropertyAccessExpression(iterator, nil, f.NewIdentifier("next"), ast.NodeFlagsNone), nil, nil, @@ -435,13 +435,13 @@ func (tx *forawaitTransformer) transformForAwaitOfStatement(node *ast.ForInOrOfS // Build the for statement iteratorDecl := f.NewVariableDeclaration(iterator, nil, nil, initializer) - iteratorDecl.Loc = node.Expression.Loc + iteratorDecl.Loc = node.Expression().Loc varDeclList := f.NewVariableDeclarationList(f.NewNodeList([]*ast.Node{ f.NewVariableDeclaration(nonUserCode, nil, nil, f.NewKeywordExpression(ast.KindTrueKeyword)), iteratorDecl, f.NewVariableDeclaration(result, nil, nil, nil), }), ast.NodeFlagsNone) - varDeclList.Loc = node.Expression.Loc + varDeclList.Loc = node.Expression().Loc condition := f.InlineExpressions([]*ast.Node{ f.NewAssignmentExpression(result, tx.createDownlevelAwait(callNext)), @@ -536,7 +536,7 @@ func (tx *forawaitTransformer) visitConstructorDeclaration(node *ast.Node) *ast. decl, decl.Modifiers(), nil, /*typeParameters*/ - tx.EmitContext().VisitParameters(decl.Parameters, tx.Visitor()), + tx.EmitContext().VisitParameters(decl.Parameters(), tx.Visitor()), nil, /*returnType*/ nil, /*fullSignature*/ tx.EmitContext().VisitFunctionBody(node.Body(), tx.Visitor()), @@ -554,7 +554,7 @@ func (tx *forawaitTransformer) visitGetAccessorDeclaration(node *ast.Node) *ast. decl.Modifiers(), tx.Visitor().VisitNode(decl.Name()), nil, /*typeParameters*/ - tx.EmitContext().VisitParameters(decl.Parameters, tx.Visitor()), + tx.EmitContext().VisitParameters(decl.Parameters(), tx.Visitor()), nil, /*returnType*/ nil, /*fullSignature*/ tx.EmitContext().VisitFunctionBody(node.Body(), tx.Visitor()), @@ -572,7 +572,7 @@ func (tx *forawaitTransformer) visitSetAccessorDeclaration(node *ast.Node) *ast. decl.Modifiers(), tx.Visitor().VisitNode(decl.Name()), nil, /*typeParameters*/ - tx.EmitContext().VisitParameters(decl.Parameters, tx.Visitor()), + tx.EmitContext().VisitParameters(decl.Parameters(), tx.Visitor()), nil, /*returnType*/ nil, /*fullSignature*/ tx.EmitContext().VisitFunctionBody(node.Body(), tx.Visitor()), @@ -597,7 +597,7 @@ func (tx *forawaitTransformer) visitMethodDeclaration(node *ast.Node) *ast.Node if tx.enclosingFunctionFlags&ast.FunctionFlagsAsync != 0 { asteriskToken = nil } else { - asteriskToken = decl.AsteriskToken + asteriskToken = decl.AsteriskToken() } var parameters *ast.NodeList @@ -606,7 +606,7 @@ func (tx *forawaitTransformer) visitMethodDeclaration(node *ast.Node) *ast.Node parameters = tx.transformAsyncGeneratorFunctionParameterList(node) body = tx.transformAsyncGeneratorFunctionBody(node) } else { - parameters = tx.EmitContext().VisitParameters(decl.Parameters, tx.Visitor()) + parameters = tx.EmitContext().VisitParameters(decl.Parameters(), tx.Visitor()) body = tx.EmitContext().VisitFunctionBody(node.Body(), tx.Visitor()) } @@ -642,7 +642,7 @@ func (tx *forawaitTransformer) visitFunctionDeclaration(node *ast.Node) *ast.Nod if tx.enclosingFunctionFlags&ast.FunctionFlagsAsync != 0 { asteriskToken = nil } else { - asteriskToken = decl.AsteriskToken + asteriskToken = decl.AsteriskToken() } var parameters *ast.NodeList @@ -651,7 +651,7 @@ func (tx *forawaitTransformer) visitFunctionDeclaration(node *ast.Node) *ast.Nod parameters = tx.transformAsyncGeneratorFunctionParameterList(node) body = tx.transformAsyncGeneratorFunctionBody(node) } else { - parameters = tx.EmitContext().VisitParameters(decl.Parameters, tx.Visitor()) + parameters = tx.EmitContext().VisitParameters(decl.Parameters(), tx.Visitor()) body = tx.EmitContext().VisitFunctionBody(node.Body(), tx.Visitor()) } @@ -678,10 +678,10 @@ func (tx *forawaitTransformer) visitArrowFunction(node *ast.Node) *ast.Node { decl, decl.Modifiers(), nil, /*typeParameters*/ - tx.EmitContext().VisitParameters(decl.Parameters, tx.Visitor()), + tx.EmitContext().VisitParameters(decl.Parameters(), tx.Visitor()), nil, /*returnType*/ nil, /*fullSignature*/ - decl.EqualsGreaterThanToken, + decl.EqualsGreaterThanToken(), tx.EmitContext().VisitFunctionBody(node.Body(), tx.Visitor()), ) tx.enclosingFunctionFlags = savedEnclosingFunctionFlags @@ -704,7 +704,7 @@ func (tx *forawaitTransformer) visitFunctionExpression(node *ast.Node) *ast.Node if tx.enclosingFunctionFlags&ast.FunctionFlagsAsync != 0 { asteriskToken = nil } else { - asteriskToken = decl.AsteriskToken + asteriskToken = decl.AsteriskToken() } var parameters *ast.NodeList @@ -713,7 +713,7 @@ func (tx *forawaitTransformer) visitFunctionExpression(node *ast.Node) *ast.Node parameters = tx.transformAsyncGeneratorFunctionParameterList(node) body = tx.transformAsyncGeneratorFunctionBody(node) } else { - parameters = tx.EmitContext().VisitParameters(decl.Parameters, tx.Visitor()) + parameters = tx.EmitContext().VisitParameters(decl.Parameters(), tx.Visitor()) body = tx.EmitContext().VisitFunctionBody(node.Body(), tx.Visitor()) } @@ -740,7 +740,7 @@ func (tx *forawaitTransformer) transformAsyncGeneratorFunctionParameterList(node var newParameters []*ast.Node for _, parameter := range node.Parameters() { param := parameter.AsParameterDeclaration() - if param.Initializer != nil || param.DotDotDotToken != nil { + if param.Initializer() != nil || param.DotDotDotToken() != nil { break } newParameter := tx.Factory().NewParameterDeclaration( diff --git a/tsc/internal/transformers/estransforms/logicalassignment.go b/tsc/internal/transformers/estransforms/logicalassignment.go index 7cf03fc0183e4..c0a95d3ddd5b7 100644 --- a/tsc/internal/transformers/estransforms/logicalassignment.go +++ b/tsc/internal/transformers/estransforms/logicalassignment.go @@ -23,7 +23,7 @@ func (ch *logicalAssignmentTransformer) visit(node *ast.Node) *ast.Node { func (ch *logicalAssignmentTransformer) visitBinaryExpression(node *ast.BinaryExpression) *ast.Node { var nonAssignmentOperator ast.Kind - switch node.OperatorToken.Kind { + switch node.OperatorToken().Kind { case ast.KindBarBarEqualsToken: nonAssignmentOperator = ast.KindBarBarToken case ast.KindAmpersandAmpersandEqualsToken: @@ -34,9 +34,9 @@ func (ch *logicalAssignmentTransformer) visitBinaryExpression(node *ast.BinaryEx return ch.Visitor().VisitEachChild(node.AsNode()) } - left := ast.SkipParentheses(ch.Visitor().VisitNode(node.Left)) + left := ast.SkipParentheses(ch.Visitor().VisitNode(node.Left())) assignmentTarget := left - right := ast.SkipParentheses(ch.Visitor().VisitNode(node.Right)) + right := ast.SkipParentheses(ch.Visitor().VisitNode(node.Right())) if ast.IsAccessExpression(left) { propertyAccessTargetSimpleCopiable := transformers.IsSimpleCopiableExpression(left.Expression()) @@ -65,15 +65,15 @@ func (ch *logicalAssignmentTransformer) visitBinaryExpression(node *ast.BinaryEx ast.NodeFlagsNone, ) } else { - elementAccessArgumentSimpleCopiable := transformers.IsSimpleCopiableExpression(left.AsElementAccessExpression().ArgumentExpression) - elementAccessArgument := left.AsElementAccessExpression().ArgumentExpression + elementAccessArgumentSimpleCopiable := transformers.IsSimpleCopiableExpression(left.AsElementAccessExpression().ArgumentExpression()) + elementAccessArgument := left.AsElementAccessExpression().ArgumentExpression() argumentExpr := elementAccessArgument if !elementAccessArgumentSimpleCopiable { elementAccessArgument = ch.Factory().NewTempVariable() ch.EmitContext().AddVariableDeclaration(elementAccessArgument) argumentExpr = ch.Factory().NewAssignmentExpression( elementAccessArgument, - left.AsElementAccessExpression().ArgumentExpression, + left.AsElementAccessExpression().ArgumentExpression(), ) } diff --git a/tsc/internal/transformers/estransforms/namedevaluation.go b/tsc/internal/transformers/estransforms/namedevaluation.go index 3b986a5b9d009..923ad9b08fc32 100644 --- a/tsc/internal/transformers/estransforms/namedevaluation.go +++ b/tsc/internal/transformers/estransforms/namedevaluation.go @@ -14,15 +14,15 @@ import ( * @internal */ func isClassNamedEvaluationHelperBlock(emitContext *printer.EmitContext, node *ast.Node) bool { - if !ast.IsClassStaticBlockDeclaration(node) || len(node.AsClassStaticBlockDeclaration().Body.Statements()) != 1 { + if !ast.IsClassStaticBlockDeclaration(node) || len(node.AsClassStaticBlockDeclaration().Body().Statements()) != 1 { return false } - statement := node.AsClassStaticBlockDeclaration().Body.Statements()[0] + statement := node.AsClassStaticBlockDeclaration().Body().Statements()[0] if ast.IsExpressionStatement(statement) { expression := statement.Expression() if emitContext.IsCallToHelper(expression, "__setFunctionName") { - arguments := expression.AsCallExpression().Arguments + arguments := expression.AsCallExpression().Arguments() return len(arguments.Nodes) >= 2 && arguments.Nodes[1] == emitContext.AssignedName(node.AsNode()) } @@ -92,11 +92,11 @@ func isNamedEvaluationAnd(emitContext *printer.EmitContext, node *ast.Node, cb f } switch node.Kind { case ast.KindShorthandPropertyAssignment: - return isAnonymousFunctionDefinition(emitContext, node.AsShorthandPropertyAssignment().ObjectAssignmentInitializer, cb) + return isAnonymousFunctionDefinition(emitContext, node.AsShorthandPropertyAssignment().ObjectAssignmentInitializer(), cb) case ast.KindPropertyAssignment, ast.KindVariableDeclaration, ast.KindParameter, ast.KindBindingElement, ast.KindPropertyDeclaration: return isAnonymousFunctionDefinition(emitContext, node.Initializer(), cb) case ast.KindBinaryExpression: - return isAnonymousFunctionDefinition(emitContext, node.AsBinaryExpression().Right, cb) + return isAnonymousFunctionDefinition(emitContext, node.AsBinaryExpression().Right(), cb) case ast.KindExportAssignment: return isAnonymousFunctionDefinition(emitContext, node.Expression(), cb) default: @@ -222,7 +222,7 @@ func injectClassNamedEvaluationHelperBlockIfMissing( node.Modifiers(), node.Name(), node.TypeParameterList(), - node.AsClassDeclaration().HeritageClauses, + node.AsClassDeclaration().HeritageClauses(), membersList, ) } else { @@ -231,7 +231,7 @@ func injectClassNamedEvaluationHelperBlockIfMissing( node.Modifiers(), node.Name(), node.TypeParameterList(), - node.AsClassExpression().HeritageClauses, + node.AsClassExpression().HeritageClauses(), membersList, ) } @@ -280,7 +280,7 @@ func transformNamedEvaluationOfPropertyAssignment(context *printer.EmitContext, factory := context.Factory assignedName, name := getAssignedNameOfPropertyName(context, node.Name(), assignedNameText) - initializer := finishTransformNamedEvaluation(context, node.Initializer, assignedName, ignoreEmptyStringLiteral) + initializer := finishTransformNamedEvaluation(context, node.Initializer(), assignedName, ignoreEmptyStringLiteral) return factory.UpdatePropertyAssignment(node, nil /*modifiers*/, name, nil /*postfixToken*/, nil /*typeNode*/, initializer) } @@ -298,16 +298,16 @@ func transformNamedEvaluationOfShorthandAssignmentProperty(emitContext *printer. if len(assignedNameText) > 0 { assignedName = factory.NewStringLiteral(assignedNameText, ast.TokenFlagsNone) } else { - assignedName = getAssignedNameOfIdentifier(emitContext, node.Name(), node.ObjectAssignmentInitializer) + assignedName = getAssignedNameOfIdentifier(emitContext, node.Name(), node.ObjectAssignmentInitializer()) } - objectAssignmentInitializer := finishTransformNamedEvaluation(emitContext, node.ObjectAssignmentInitializer, assignedName, ignoreEmptyStringLiteral) + objectAssignmentInitializer := finishTransformNamedEvaluation(emitContext, node.ObjectAssignmentInitializer(), assignedName, ignoreEmptyStringLiteral) return factory.UpdateShorthandPropertyAssignment( node, nil, /*modifiers*/ node.Name(), nil, /*postfixToken*/ nil, /*typeNode*/ - node.EqualsToken, + node.EqualsToken(), objectAssignmentInitializer, ) } @@ -332,9 +332,9 @@ func transformNamedEvaluationOfVariableDeclaration(emitContext *printer.EmitCont if len(assignedNameText) > 0 { assignedName = factory.NewStringLiteral(assignedNameText, ast.TokenFlagsNone) } else { - assignedName = getAssignedNameOfIdentifier(emitContext, node.Name(), node.Initializer) + assignedName = getAssignedNameOfIdentifier(emitContext, node.Name(), node.Initializer()) } - initializer := finishTransformNamedEvaluation(emitContext, node.Initializer, assignedName, ignoreEmptyStringLiteral) + initializer := finishTransformNamedEvaluation(emitContext, node.Initializer(), assignedName, ignoreEmptyStringLiteral) return factory.UpdateVariableDeclaration( node, node.Name(), @@ -366,13 +366,13 @@ func transformNamedEvaluationOfParameterDeclaration(emitContext *printer.EmitCon if len(assignedNameText) > 0 { assignedName = factory.NewStringLiteral(assignedNameText, ast.TokenFlagsNone) } else { - assignedName = getAssignedNameOfIdentifier(emitContext, node.Name(), node.Initializer) + assignedName = getAssignedNameOfIdentifier(emitContext, node.Name(), node.Initializer()) } - initializer := finishTransformNamedEvaluation(emitContext, node.Initializer, assignedName, ignoreEmptyStringLiteral) + initializer := finishTransformNamedEvaluation(emitContext, node.Initializer(), assignedName, ignoreEmptyStringLiteral) return factory.UpdateParameterDeclaration( node, nil, /*modifiers*/ - node.DotDotDotToken, + node.DotDotDotToken(), node.Name(), nil, /*questionToken*/ nil, /*typeNode*/ @@ -402,13 +402,13 @@ func transformNamedEvaluationOfBindingElement(emitContext *printer.EmitContext, if len(assignedNameText) > 0 { assignedName = factory.NewStringLiteral(assignedNameText, ast.TokenFlagsNone) } else { - assignedName = getAssignedNameOfIdentifier(emitContext, node.Name(), node.Initializer) + assignedName = getAssignedNameOfIdentifier(emitContext, node.Name(), node.Initializer()) } - initializer := finishTransformNamedEvaluation(emitContext, node.Initializer, assignedName, ignoreEmptyStringLiteral) + initializer := finishTransformNamedEvaluation(emitContext, node.Initializer(), assignedName, ignoreEmptyStringLiteral) return factory.UpdateBindingElement( node, - node.DotDotDotToken, - node.PropertyName, + node.DotDotDotToken(), + node.PropertyName(), node.Name(), initializer, ) @@ -424,7 +424,7 @@ func transformNamedEvaluationOfPropertyDeclaration(emitContext *printer.EmitCont factory := emitContext.Factory assignedName, name := getAssignedNameOfPropertyName(emitContext, node.Name(), assignedNameText) - initializer := finishTransformNamedEvaluation(emitContext, node.Initializer, assignedName, ignoreEmptyStringLiteral) + initializer := finishTransformNamedEvaluation(emitContext, node.Initializer(), assignedName, ignoreEmptyStringLiteral) return factory.UpdatePropertyDeclaration( node, node.Modifiers(), @@ -467,15 +467,15 @@ func transformNamedEvaluationOfAssignmentExpression(emitContext *printer.EmitCon if len(assignedNameText) > 0 { assignedName = factory.NewStringLiteral(assignedNameText, ast.TokenFlagsNone) } else { - assignedName = getAssignedNameOfIdentifier(emitContext, node.Left, node.Right) + assignedName = getAssignedNameOfIdentifier(emitContext, node.Left(), node.Right()) } - right := finishTransformNamedEvaluation(emitContext, node.Right, assignedName, ignoreEmptyStringLiteral) + right := finishTransformNamedEvaluation(emitContext, node.Right(), assignedName, ignoreEmptyStringLiteral) return factory.UpdateBinaryExpression( node, nil, /*modifiers*/ - node.Left, + node.Left(), nil, /*typeNode*/ - node.OperatorToken, + node.OperatorToken(), right, ) } @@ -499,7 +499,7 @@ func transformNamedEvaluationOfExportAssignment(emitContext *printer.EmitContext } else { assignedName = factory.NewStringLiteral("default", ast.TokenFlagsNone) } - expression := finishTransformNamedEvaluation(emitContext, node.Expression, assignedName, ignoreEmptyStringLiteral) + expression := finishTransformNamedEvaluation(emitContext, node.Expression(), assignedName, ignoreEmptyStringLiteral) return factory.UpdateExportAssignment( node, nil, /*modifiers*/ diff --git a/tsc/internal/transformers/estransforms/nullishcoalescing.go b/tsc/internal/transformers/estransforms/nullishcoalescing.go index 4ae49ccd90faa..7cecbe458765b 100644 --- a/tsc/internal/transformers/estransforms/nullishcoalescing.go +++ b/tsc/internal/transformers/estransforms/nullishcoalescing.go @@ -22,9 +22,9 @@ func (ch *nullishCoalescingTransformer) visit(node *ast.Node) *ast.Node { } func (ch *nullishCoalescingTransformer) visitBinaryExpression(node *ast.BinaryExpression) *ast.Node { - switch node.OperatorToken.Kind { + switch node.OperatorToken().Kind { case ast.KindQuestionQuestionToken: - left := ch.Visitor().VisitNode(node.Left) + left := ch.Visitor().VisitNode(node.Left()) right := left if !transformers.IsSimpleCopiableExpression(left) { right = ch.Factory().NewTempVariable() @@ -36,7 +36,7 @@ func (ch *nullishCoalescingTransformer) visitBinaryExpression(node *ast.BinaryEx ch.Factory().NewToken(ast.KindQuestionToken), right, ch.Factory().NewToken(ast.KindColonToken), - ch.Visitor().VisitNode(node.Right), + ch.Visitor().VisitNode(node.Right()), ) default: return ch.Visitor().VisitEachChild(node.AsNode()) diff --git a/tsc/internal/transformers/estransforms/objectrestspread.go b/tsc/internal/transformers/estransforms/objectrestspread.go index 3c0ebae147a19..8aa0c2b642fc5 100644 --- a/tsc/internal/transformers/estransforms/objectrestspread.go +++ b/tsc/internal/transformers/estransforms/objectrestspread.go @@ -84,7 +84,7 @@ func (ch *objectRestSpreadTransformer) visitParameter(node *ast.ParameterDeclara return ch.Factory().UpdateParameterDeclaration( node, nil, - node.DotDotDotToken, + node.DotDotDotToken(), name, nil, nil, @@ -98,11 +98,11 @@ func (ch *objectRestSpreadTransformer) visitParameter(node *ast.ParameterDeclara return ch.Factory().UpdateParameterDeclaration( node, nil, - node.DotDotDotToken, + node.DotDotDotToken(), ch.Factory().NewGeneratedNameForNode(node.AsNode()), nil, nil, - ch.Visitor().VisitNode(node.Initializer), + ch.Visitor().VisitNode(node.Initializer()), ) } return ch.Visitor().VisitEachChild(node.AsNode()) @@ -139,7 +139,7 @@ func (ch *objectRestSpreadTransformer) visitContructorDeclaration(node *ast.Cons node, node.Modifiers(), nil, - ch.Visitor().VisitNodes(node.Parameters), + ch.Visitor().VisitNodes(node.Parameters()), nil, nil, ch.transformFunctionBody(node.AsNode()), @@ -154,7 +154,7 @@ func (ch *objectRestSpreadTransformer) visitGetAccessorDeclaration(node *ast.Get node.Modifiers(), ch.Visitor().VisitNode(node.Name()), nil, - ch.Visitor().VisitNodes(node.Parameters), + ch.Visitor().VisitNodes(node.Parameters()), nil, nil, ch.transformFunctionBody(node.AsNode()), @@ -169,7 +169,7 @@ func (ch *objectRestSpreadTransformer) visitSetAccessorDeclaration(node *ast.Set node.Modifiers(), ch.Visitor().VisitNode(node.Name()), nil, - ch.Visitor().VisitNodes(node.Parameters), + ch.Visitor().VisitNodes(node.Parameters()), nil, nil, ch.transformFunctionBody(node.AsNode()), @@ -182,11 +182,11 @@ func (ch *objectRestSpreadTransformer) visitMethodDeclaration(node *ast.MethodDe return ch.Factory().UpdateMethodDeclaration( node, node.Modifiers(), - node.AsteriskToken, + node.AsteriskToken(), ch.Visitor().VisitNode(node.Name()), - node.PostfixToken, + node.PostfixToken(), nil, - ch.Visitor().VisitNodes(node.Parameters), + ch.Visitor().VisitNodes(node.Parameters()), nil, nil, ch.transformFunctionBody(node.AsNode()), @@ -199,10 +199,10 @@ func (ch *objectRestSpreadTransformer) visitFunctionDeclaration(node *ast.Functi return ch.Factory().UpdateFunctionDeclaration( node, node.Modifiers(), - node.AsteriskToken, + node.AsteriskToken(), ch.Visitor().VisitNode(node.Name()), nil, - ch.Visitor().VisitNodes(node.Parameters), + ch.Visitor().VisitNodes(node.Parameters()), nil, nil, ch.transformFunctionBody(node.AsNode()), @@ -216,10 +216,10 @@ func (ch *objectRestSpreadTransformer) visitArrowFunction(node *ast.ArrowFunctio node, node.Modifiers(), nil, - ch.Visitor().VisitNodes(node.Parameters), + ch.Visitor().VisitNodes(node.Parameters()), nil, nil, - node.EqualsGreaterThanToken, + node.EqualsGreaterThanToken(), ch.transformFunctionBody(node.AsNode()), ) } @@ -230,10 +230,10 @@ func (ch *objectRestSpreadTransformer) visitFunctionExpression(node *ast.Functio return ch.Factory().UpdateFunctionExpression( node, node.Modifiers(), - node.AsteriskToken, + node.AsteriskToken(), ch.Visitor().VisitNode(node.Name()), nil, - ch.Visitor().VisitNodes(node.Parameters), + ch.Visitor().VisitNodes(node.Parameters()), nil, nil, ch.transformFunctionBody(node.AsNode()), @@ -306,7 +306,7 @@ func (ch *objectRestSpreadTransformer) collectObjectRestAssignments(node *ast.No if declarations.Kind == ast.KindSyntaxList { decls = declarations.AsSyntaxList().Children } - declarationList.AsVariableDeclarationList().Declarations.Nodes = append(declarationList.AsVariableDeclarationList().Declarations.Nodes, decls...) + declarationList.AsVariableDeclarationList().Declarations().SetNodes(append(declarationList.AsVariableDeclarationList().Declarations().Nodes, decls...)) statement := ch.Factory().NewVariableStatement(nil, declarationList) ch.EmitContext().AddEmitFlags(statement, printer.EFCustomPrologue) results = append(results, statement) @@ -364,7 +364,7 @@ func (ch *objectRestSpreadTransformer) collectObjectRestAssignments(node *ast.No if declarations.Kind == ast.KindSyntaxList { decls = declarations.AsSyntaxList().Children } - declarationList.AsVariableDeclarationList().Declarations.Nodes = append(declarationList.AsVariableDeclarationList().Declarations.Nodes, decls...) + declarationList.AsVariableDeclarationList().Declarations().SetNodes(append(declarationList.AsVariableDeclarationList().Declarations().Nodes, decls...)) statement := ch.Factory().NewVariableStatement(nil, declarationList) ch.EmitContext().AddEmitFlags(statement, printer.EFCustomPrologue) results = append(results, statement) @@ -376,15 +376,15 @@ func (ch *objectRestSpreadTransformer) collectObjectRestAssignments(node *ast.No } func (ch *objectRestSpreadTransformer) visitCatchClause(node *ast.CatchClause) *ast.Node { - if node.VariableDeclaration != nil && ast.IsBindingPattern(node.VariableDeclaration.Name()) && node.VariableDeclaration.Name().SubtreeFacts()&ast.SubtreeContainsObjectRestOrSpread != 0 { - name := ch.Factory().NewGeneratedNameForNode(node.VariableDeclaration.Name()) - updatedDecl := ch.Factory().UpdateVariableDeclaration(node.VariableDeclaration.AsVariableDeclaration(), node.VariableDeclaration.Name(), nil, nil, name) + if node.VariableDeclaration() != nil && ast.IsBindingPattern(node.VariableDeclaration().Name()) && node.VariableDeclaration().Name().SubtreeFacts()&ast.SubtreeContainsObjectRestOrSpread != 0 { + name := ch.Factory().NewGeneratedNameForNode(node.VariableDeclaration().Name()) + updatedDecl := ch.Factory().UpdateVariableDeclaration(node.VariableDeclaration().AsVariableDeclaration(), node.VariableDeclaration().Name(), nil, nil, name) visitedBindings := transformers.FlattenDestructuringBinding( &ch.Transformer, updatedDecl, nil, transformers.FlattenLevelObjectRest, false, false, ) - block := ch.Visitor().VisitNode(node.Block) + block := ch.Visitor().VisitNode(node.Block()) if visitedBindings != nil { var decls []*ast.Node if visitedBindings.Kind == ast.KindSyntaxList { @@ -402,7 +402,7 @@ func (ch *objectRestSpreadTransformer) visitCatchClause(node *ast.CatchClause) * } return ch.Factory().UpdateCatchClause( node, - ch.Factory().UpdateVariableDeclaration(node.VariableDeclaration.AsVariableDeclaration(), name, nil, nil, nil), + ch.Factory().UpdateVariableDeclaration(node.VariableDeclaration().AsVariableDeclaration(), name, nil, nil, nil), block, ) } @@ -443,8 +443,8 @@ func (ch *objectRestSpreadTransformer) visitVariableDeclarationWorker(node *ast. } func (ch *objectRestSpreadTransformer) visitForOftatement(node *ast.ForInOrOfStatement) *ast.Node { - if node.Initializer.SubtreeFacts()&ast.SubtreeContainsObjectRestOrSpread != 0 || (ast.IsAssignmentPattern(node.Initializer) && ast.ContainsObjectRestOrSpread(node.Initializer)) { - initializerWithoutParens := ast.SkipParentheses(node.Initializer) + if node.Initializer().SubtreeFacts()&ast.SubtreeContainsObjectRestOrSpread != 0 || (ast.IsAssignmentPattern(node.Initializer()) && ast.ContainsObjectRestOrSpread(node.Initializer())) { + initializerWithoutParens := ast.SkipParentheses(node.Initializer()) if ast.IsVariableDeclarationList(initializerWithoutParens) || ast.IsAssignmentPattern(initializerWithoutParens) { var bodyLocation core.TextRange var statementsLocation core.TextRange @@ -454,28 +454,28 @@ func (ch *objectRestSpreadTransformer) visitForOftatement(node *ast.ForInOrOfSta if res != nil { statements = append(statements, res) } - if ast.IsBlock(node.Statement) { - for _, statement := range node.Statement.Statements() { + if ast.IsBlock(node.Statement()) { + for _, statement := range node.Statement().Statements() { visited := ch.Visitor().VisitEachChild(statement) if visited != nil { statements = append(statements, visited) } } - bodyLocation = node.Statement.Loc - statementsLocation = node.Statement.StatementList().Loc - } else if node.Statement != nil { - statements = append(statements, ch.Visitor().VisitEachChild(node.Statement)) - bodyLocation = node.Statement.Loc - statementsLocation = node.Statement.Loc + bodyLocation = node.Statement().Loc + statementsLocation = node.Statement().StatementList().Loc + } else if node.Statement() != nil { + statements = append(statements, ch.Visitor().VisitEachChild(node.Statement())) + bodyLocation = node.Statement().Loc + statementsLocation = node.Statement().Loc } list := ch.Factory().NewVariableDeclarationList( ch.Factory().NewNodeList([]*ast.Node{ch.Factory().NewVariableDeclaration(temp, nil, nil, nil)}), ast.NodeFlagsLet, ) - list.Loc = node.Initializer.Loc + list.Loc = node.Initializer().Loc - expr := ch.Visitor().VisitEachChild(node.Expression) + expr := ch.Visitor().VisitEachChild(node.Expression()) statementsList := ch.Factory().NewNodeList(statements) statementsList.Loc = statementsLocation @@ -485,7 +485,7 @@ func (ch *objectRestSpreadTransformer) visitForOftatement(node *ast.ForInOrOfSta return ch.Factory().UpdateForInOrOfStatement( node, - node.AwaitModifier, + node.AwaitModifier(), list, expr, block, @@ -496,19 +496,19 @@ func (ch *objectRestSpreadTransformer) visitForOftatement(node *ast.ForInOrOfSta } func (ch *objectRestSpreadTransformer) visitBinaryExpression(node *ast.BinaryExpression, expressionResultIsUnused bool) *ast.Node { - if ast.IsDestructuringAssignment(node.AsNode()) && ast.ContainsObjectRestOrSpread(node.Left) { + if ast.IsDestructuringAssignment(node.AsNode()) && ast.ContainsObjectRestOrSpread(node.Left()) { return transformers.FlattenDestructuringAssignment( &ch.Transformer, node.AsNode(), !expressionResultIsUnused, transformers.FlattenLevelObjectRest, nil, ) } - if node.OperatorToken.Kind == ast.KindCommaToken { + if node.OperatorToken().Kind == ast.KindCommaToken { ch.expressionResultIsUnused = true - left := ch.Visitor().VisitNode(node.Left) + left := ch.Visitor().VisitNode(node.Left()) ch.expressionResultIsUnused = expressionResultIsUnused - right := ch.Visitor().VisitNode(node.Right) - return ch.Factory().UpdateBinaryExpression(node, nil, left, nil, node.OperatorToken, right) + right := ch.Visitor().VisitNode(node.Right()) + return ch.Factory().UpdateBinaryExpression(node, nil, left, nil, node.OperatorToken(), right) } return ch.Visitor().VisitEachChild(node.AsNode()) } @@ -539,7 +539,7 @@ func (ch *objectRestSpreadTransformer) visitObjectLiteralExpression(node *ast.Ob // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we // end up with `{ a: 1, b: 2, c: 3 }` - objects := ch.chunkObjectLiteralElements(node.Properties) + objects := ch.chunkObjectLiteralElements(node.Properties()) if len(objects) > 0 && objects[0].Kind != ast.KindObjectLiteralExpression { objects = append([]*ast.Node{ch.Factory().NewObjectLiteralExpression(ch.Factory().NewNodeList(nil), false)}, objects...) } diff --git a/tsc/internal/transformers/estransforms/optionalcatch.go b/tsc/internal/transformers/estransforms/optionalcatch.go index f5cf685b2d14e..76e0bcf5c00d3 100644 --- a/tsc/internal/transformers/estransforms/optionalcatch.go +++ b/tsc/internal/transformers/estransforms/optionalcatch.go @@ -22,10 +22,10 @@ func (ch *optionalCatchTransformer) visit(node *ast.Node) *ast.Node { } func (ch *optionalCatchTransformer) visitCatchClause(node *ast.CatchClause) *ast.Node { - if node.VariableDeclaration == nil { + if node.VariableDeclaration() == nil { return ch.Factory().NewCatchClause( ch.Factory().NewVariableDeclaration(ch.Factory().NewTempVariable(), nil, nil, nil), - ch.Visitor().Visit(node.Block), + ch.Visitor().Visit(node.Block()), ) } return ch.Visitor().VisitEachChild(node.AsNode()) diff --git a/tsc/internal/transformers/estransforms/optionalchain.go b/tsc/internal/transformers/estransforms/optionalchain.go index 33b269280f594..66f64bcd9c317 100644 --- a/tsc/internal/transformers/estransforms/optionalchain.go +++ b/tsc/internal/transformers/estransforms/optionalchain.go @@ -36,14 +36,14 @@ func (ch *optionalChainTransformer) visitCallExpression(node *ast.CallExpression // If `node` is an optional chain, then it is the outermost chain of an optional expression. return ch.visitOptionalExpression(node.AsNode(), captureThisArg, false) } - if ast.IsParenthesizedExpression(node.Expression) { - unwrapped := ast.SkipParentheses(node.Expression) + if ast.IsParenthesizedExpression(node.Expression()) { + unwrapped := ast.SkipParentheses(node.Expression()) if unwrapped.Flags&ast.NodeFlagsOptionalChain != 0 { // capture thisArg for calls of parenthesized optional chains like `(foo?.bar)()` - expression := ch.visitParenthesizedExpression(node.Expression.AsParenthesizedExpression(), true, false) - args := ch.Visitor().VisitNodes(node.Arguments) + expression := ch.visitParenthesizedExpression(node.Expression().AsParenthesizedExpression(), true, false) + args := ch.Visitor().VisitNodes(node.Arguments()) if ast.IsSyntheticReferenceExpression(expression) { - res := ch.Factory().NewFunctionCallCall(expression.AsSyntheticReferenceExpression().Expression, expression.AsSyntheticReferenceExpression().ThisArg, args.Nodes) + res := ch.Factory().NewFunctionCallCall(expression.AsSyntheticReferenceExpression().Expression(), expression.AsSyntheticReferenceExpression().ThisArg(), args.Nodes) res.Loc = node.Loc ch.EmitContext().SetOriginal(res, node.AsNode()) return res @@ -55,12 +55,12 @@ func (ch *optionalChainTransformer) visitCallExpression(node *ast.CallExpression } func (ch *optionalChainTransformer) visitParenthesizedExpression(node *ast.ParenthesizedExpression, captureThisArg bool, isDelete bool) *ast.Node { - expr := ch.visitNonOptionalExpression(node.Expression, captureThisArg, isDelete) + expr := ch.visitNonOptionalExpression(node.Expression(), captureThisArg, isDelete) if ast.IsSyntheticReferenceExpression(expr) { // `(a.b)` -> { expression `((_a = a).b)`, thisArg: `_a` } // `(a[b])` -> { expression `((_a = a)[b])`, thisArg: `_a` } synth := expr.AsSyntheticReferenceExpression() - res := ch.Factory().NewSyntheticReferenceExpression(ch.Factory().UpdateParenthesizedExpression(node, synth.Expression), synth.ThisArg) + res := ch.Factory().NewSyntheticReferenceExpression(ch.Factory().UpdateParenthesizedExpression(node, synth.Expression()), synth.ThisArg()) ch.EmitContext().SetOriginal(res, node.AsNode()) return res } @@ -91,7 +91,7 @@ func (ch *optionalChainTransformer) visitPropertyOrElementAccessExpression(node expression = ch.Factory().UpdatePropertyAccessExpression(p, expression, nil /*questionDotToken*/, ch.Visitor().VisitNode(p.Name()), p.Flags) } else { p := node.AsElementAccessExpression() - expression = ch.Factory().UpdateElementAccessExpression(p, expression, nil, ch.Visitor().VisitNode(p.AsElementAccessExpression().ArgumentExpression), p.Flags) + expression = ch.Factory().UpdateElementAccessExpression(p, expression, nil, ch.Visitor().VisitNode(p.AsElementAccessExpression().ArgumentExpression()), p.Flags) } if thisArg != nil { @@ -103,9 +103,9 @@ func (ch *optionalChainTransformer) visitPropertyOrElementAccessExpression(node } func (ch *optionalChainTransformer) visitDeleteExpression(node *ast.DeleteExpression) *ast.Node { - unwrapped := ast.SkipParentheses(node.Expression) + unwrapped := ast.SkipParentheses(node.Expression()) if unwrapped.Flags&ast.NodeFlagsOptionalChain != 0 { - return ch.visitNonOptionalExpression(node.Expression, false, true) + return ch.visitNonOptionalExpression(node.Expression(), false, true) } return ch.Visitor().VisitEachChild(node.AsNode()) } @@ -155,8 +155,8 @@ func (ch *optionalChainTransformer) visitOptionalExpression(node *ast.Node, capt var leftThisArg *ast.Expression capturedLeft := left if ast.IsSyntheticReferenceExpression(left) { - leftThisArg = left.AsSyntheticReferenceExpression().ThisArg - capturedLeft = left.AsSyntheticReferenceExpression().Expression + leftThisArg = left.AsSyntheticReferenceExpression().ThisArg() + capturedLeft = left.AsSyntheticReferenceExpression().Expression() } leftExpression := ch.Factory().RestoreOuterExpressions(expression, capturedLeft, ast.OEKPartiallyEmittedExpressions) if !transformers.IsSimpleCopiableExpression(capturedLeft) { @@ -180,7 +180,7 @@ func (ch *optionalChainTransformer) visitOptionalExpression(node *ast.Node, capt } } if segment.Kind == ast.KindElementAccessExpression { - rightExpression = ch.Factory().NewElementAccessExpression(rightExpression, nil, ch.Visitor().VisitNode(segment.AsElementAccessExpression().ArgumentExpression), ast.NodeFlagsNone) + rightExpression = ch.Factory().NewElementAccessExpression(rightExpression, nil, ch.Visitor().VisitNode(segment.AsElementAccessExpression().ArgumentExpression()), ast.NodeFlagsNone) } else { rightExpression = ch.Factory().NewPropertyAccessExpression(rightExpression, nil, ch.Visitor().VisitNode(segment.AsPropertyAccessExpression().Name()), ast.NodeFlagsNone) } diff --git a/tsc/internal/transformers/estransforms/taggedtemplate.go b/tsc/internal/transformers/estransforms/taggedtemplate.go index 0349e7a79d13b..1ad5a416d28d5 100644 --- a/tsc/internal/transformers/estransforms/taggedtemplate.go +++ b/tsc/internal/transformers/estransforms/taggedtemplate.go @@ -69,8 +69,8 @@ func (tx *taggedTemplateTransformer) visitTaggedTemplateExpression(node *ast.Tag } func (tx *taggedTemplateTransformer) processTaggedTemplateExpression(node *ast.TaggedTemplateExpression) *ast.Node { - tag := tx.Visitor().VisitNode(node.Tag) - template := node.Template + tag := tx.Visitor().VisitNode(node.Tag()) + template := node.Template() if !hasInvalidEscape(template) { return tx.Visitor().VisitEachChild(node.AsNode()) @@ -88,13 +88,13 @@ func (tx *taggedTemplateTransformer) processTaggedTemplateExpression(node *ast.T rawStrings = append(rawStrings, getRawLiteral(f, template)) } else { te := template.AsTemplateExpression() - cookedStrings = append(cookedStrings, createTemplateCooked(f, te.Head.TemplateLiteralLikeData())) - rawStrings = append(rawStrings, getRawLiteral(f, te.Head)) - for _, span := range te.TemplateSpans.Nodes { + cookedStrings = append(cookedStrings, createTemplateCooked(f, te.Head().TemplateLiteralLikeData())) + rawStrings = append(rawStrings, getRawLiteral(f, te.Head())) + for _, span := range te.TemplateSpans().Nodes { ts := span.AsTemplateSpan() - cookedStrings = append(cookedStrings, createTemplateCooked(f, ts.Literal.TemplateLiteralLikeData())) - rawStrings = append(rawStrings, getRawLiteral(f, ts.Literal)) - templateArguments = append(templateArguments, tx.Visitor().VisitNode(ts.Expression)) + cookedStrings = append(cookedStrings, createTemplateCooked(f, ts.Literal().TemplateLiteralLikeData())) + rawStrings = append(rawStrings, getRawLiteral(f, ts.Literal())) + templateArguments = append(templateArguments, tx.Visitor().VisitNode(ts.Expression())) } } @@ -163,11 +163,11 @@ func hasInvalidEscape(template *ast.Node) bool { return template.TemplateLiteralLikeData().TemplateFlags&ast.TokenFlagsContainsInvalidEscape != 0 } te := template.AsTemplateExpression() - if te.Head.TemplateLiteralLikeData().TemplateFlags&ast.TokenFlagsContainsInvalidEscape != 0 { + if te.Head().TemplateLiteralLikeData().TemplateFlags&ast.TokenFlagsContainsInvalidEscape != 0 { return true } - for _, span := range te.TemplateSpans.Nodes { - if span.AsTemplateSpan().Literal.TemplateLiteralLikeData().TemplateFlags&ast.TokenFlagsContainsInvalidEscape != 0 { + for _, span := range te.TemplateSpans().Nodes { + if span.AsTemplateSpan().Literal().TemplateLiteralLikeData().TemplateFlags&ast.TokenFlagsContainsInvalidEscape != 0 { return true } } diff --git a/tsc/internal/transformers/estransforms/using.go b/tsc/internal/transformers/estransforms/using.go index 9becbf3201381..b52d8e5ca7130 100644 --- a/tsc/internal/transformers/estransforms/using.go +++ b/tsc/internal/transformers/estransforms/using.go @@ -190,9 +190,9 @@ func (tx *usingDeclarationTransformer) visitSourceFile(node *ast.SourceFile) *as } func (tx *usingDeclarationTransformer) visitBlock(node *ast.Block) *ast.Node { - usingKind := getUsingKindOfStatements(node.Statements.Nodes) + usingKind := getUsingKindOfStatements(node.Statements().Nodes) if usingKind != usingKindNone { - prologue, rest := tx.Factory().SplitStandardPrologue(node.Statements.Nodes) + prologue, rest := tx.Factory().SplitStandardPrologue(node.Statements().Nodes) envBinding := tx.createEnvBinding() statements := make([]*ast.Statement, 0, len(prologue)+2) statements = append(statements, core.FirstResult(tx.Visitor().VisitSlice(prologue))...) @@ -202,14 +202,14 @@ func (tx *usingDeclarationTransformer) visitBlock(node *ast.Block) *ast.Node { usingKind == usingKindAsync, )...) statementList := tx.Factory().NewNodeList(statements) - statementList.Loc = node.Statements.Loc + statementList.Loc = node.Statements().Loc return tx.Factory().UpdateBlock(node, statementList, node.MultiLine) } return tx.Visitor().VisitEachChild(node.AsNode()) } func (tx *usingDeclarationTransformer) visitForStatement(node *ast.ForStatement) *ast.Node { - if node.Initializer != nil && isUsingVariableDeclarationList(node.Initializer) { + if node.Initializer() != nil && isUsingVariableDeclarationList(node.Initializer()) { // given: // // for (using x = expr; cond; incr) { ... } @@ -224,13 +224,13 @@ func (tx *usingDeclarationTransformer) visitForStatement(node *ast.ForStatement) // before handing the shallow transformation back to the visitor for an in-depth transformation. return tx.Visitor().VisitNode( tx.Factory().NewBlock(tx.Factory().NewNodeList([]*ast.Statement{ - tx.Factory().NewVariableStatement(nil /*modifiers*/, node.Initializer), + tx.Factory().NewVariableStatement(nil /*modifiers*/, node.Initializer()), tx.Factory().UpdateForStatement( node, nil, /*initializer*/ - node.Condition, - node.Incrementor, - node.Statement, + node.Condition(), + node.Incrementor(), + node.Statement(), ), }), false /*multiLine*/), ) @@ -239,7 +239,7 @@ func (tx *usingDeclarationTransformer) visitForStatement(node *ast.ForStatement) } func (tx *usingDeclarationTransformer) visitForOfStatement(node *ast.ForInOrOfStatement) *ast.Node { - if isUsingVariableDeclarationList(node.Initializer) { + if isUsingVariableDeclarationList(node.Initializer()) { // given: // // for (using x of y) { ... } @@ -252,8 +252,8 @@ func (tx *usingDeclarationTransformer) visitForOfStatement(node *ast.ForInOrOfSt // } // // before handing the shallow transformation back to the visitor for an in-depth transformation. - forInitializer := node.Initializer.AsVariableDeclarationList() - forDecl := core.FirstOrNil(forInitializer.Declarations.Nodes) + forInitializer := node.Initializer().AsVariableDeclarationList() + forDecl := core.FirstOrNil(forInitializer.Declarations().Nodes) if forDecl == nil { forDecl = tx.Factory().NewVariableDeclaration(tx.Factory().NewTempVariable(), nil, nil, nil) } @@ -267,20 +267,20 @@ func (tx *usingDeclarationTransformer) visitForOfStatement(node *ast.ForInOrOfSt ) usingVarStatement := tx.Factory().NewVariableStatement(nil /*modifiers*/, usingVarList) var statement *ast.Statement - if ast.IsBlock(node.Statement) { - statements := make([]*ast.Statement, 0, len(node.Statement.Statements())+1) + if ast.IsBlock(node.Statement()) { + statements := make([]*ast.Statement, 0, len(node.Statement().Statements())+1) statements = append(statements, usingVarStatement) - statements = append(statements, node.Statement.Statements()...) + statements = append(statements, node.Statement().Statements()...) statement = tx.Factory().UpdateBlock( - node.Statement.AsBlock(), + node.Statement().AsBlock(), tx.Factory().NewNodeList(statements), - node.Statement.AsBlock().MultiLine, + node.Statement().AsBlock().MultiLine, ) } else { statement = tx.Factory().NewBlock( tx.Factory().NewNodeList([]*ast.Statement{ usingVarStatement, - node.Statement, + node.Statement(), }), true, /*multiLine*/ ) @@ -288,14 +288,14 @@ func (tx *usingDeclarationTransformer) visitForOfStatement(node *ast.ForInOrOfSt return tx.Visitor().VisitNode( tx.Factory().UpdateForInOrOfStatement( node, - node.AwaitModifier, + node.AwaitModifier(), tx.Factory().NewVariableDeclarationList( tx.Factory().NewNodeList([]*ast.VariableDeclarationNode{ tx.Factory().NewVariableDeclaration(temp, nil /*exclamationToken*/, nil /*type*/, nil), }), ast.NodeFlagsConst, ), - node.Expression, + node.Expression(), statement, ), ) @@ -340,9 +340,9 @@ func (tx *usingDeclarationTransformer) transformUsingDeclarations(statementsIn [ usingKind := getUsingKind(statement) if usingKind != usingKindNone { varStatement := statement.AsVariableStatement() - declarationList := varStatement.DeclarationList + declarationList := varStatement.DeclarationList() var declarations []*ast.VariableDeclarationNode - for _, declaration := range declarationList.AsVariableDeclarationList().Declarations.Nodes { + for _, declaration := range declarationList.AsVariableDeclarationList().Declarations().Nodes { if !ast.IsIdentifier(declaration.Name()) { // Since binding patterns are a grammar error, we reset `declarations` so we don't process this as a `using`. declarations = nil @@ -431,7 +431,7 @@ func (tx *usingDeclarationTransformer) hoistExportDefault(node *ast.ExportAssign tx.hoistBindingIdentifier(tx.defaultExportBinding /*isExport*/, true, tx.Factory().NewIdentifier("default"), node.AsNode()) // give a class or function expression an assigned name, if needed. - expression := node.Expression + expression := node.Expression() innerExpression := ast.SkipOuterExpressions(expression, ast.OEKAll) if isNamedEvaluation(tx.EmitContext(), innerExpression) { innerExpression = transformNamedEvaluation(tx.EmitContext(), innerExpression /*ignoreEmptyStringLiteral*/, false, "default") @@ -470,7 +470,7 @@ func (tx *usingDeclarationTransformer) hoistExportEquals(node *ast.ExportAssignm tx.EmitContext().AddVariableDeclaration(tx.exportEqualsBinding) // give a class or function expression an assigned name, if needed. - assignment := tx.Factory().NewAssignmentExpression(tx.exportEqualsBinding, node.Expression) + assignment := tx.Factory().NewAssignmentExpression(tx.exportEqualsBinding, node.Expression()) return tx.Factory().NewExpressionStatement(assignment) } @@ -563,7 +563,7 @@ func (tx *usingDeclarationTransformer) hoistVariableStatement(node *ast.Variable // NOTE: `node` has already been visited var expressions []*ast.Expression isExported := ast.HasSyntacticModifier(node.AsNode(), ast.ModifierFlagsExport) - for _, variable := range node.DeclarationList.AsVariableDeclarationList().Declarations.Nodes { + for _, variable := range node.DeclarationList().AsVariableDeclarationList().Declarations().Nodes { tx.hoistBindingElement(variable, isExported, variable) if variable.Initializer() != nil { expressions = append(expressions, tx.hoistInitializedVariable(variable.AsVariableDeclaration())) @@ -581,7 +581,7 @@ func (tx *usingDeclarationTransformer) hoistVariableStatement(node *ast.Variable func (tx *usingDeclarationTransformer) hoistInitializedVariable(node *ast.VariableDeclaration) *ast.Expression { // NOTE: `node` has already been visited - if node.Initializer == nil { + if node.Initializer() == nil { panic("Expected initializer") } var target *ast.Expression @@ -592,7 +592,7 @@ func (tx *usingDeclarationTransformer) hoistInitializedVariable(node *ast.Variab target = transformers.ConvertBindingPatternToAssignmentPattern(tx.EmitContext(), node.Name().AsBindingPattern()) } - assignment := tx.Factory().NewAssignmentExpression(target, node.Initializer) + assignment := tx.Factory().NewAssignmentExpression(target, node.Initializer()) tx.EmitContext().SetOriginal(assignment, node.AsNode()) tx.EmitContext().SetCommentRange(assignment, node.Loc) tx.EmitContext().SetSourceMapRange(assignment, node.Loc) @@ -774,7 +774,7 @@ func getUsingKindOfVariableDeclarationList(node *ast.VariableDeclarationList) us } func getUsingKindOfVariableStatement(node *ast.VariableStatement) usingKind { - return getUsingKindOfVariableDeclarationList(node.DeclarationList.AsVariableDeclarationList()) + return getUsingKindOfVariableDeclarationList(node.DeclarationList().AsVariableDeclarationList()) } func getUsingKind(statement *ast.Node) usingKind { diff --git a/tsc/internal/transformers/estransforms/utilities.go b/tsc/internal/transformers/estransforms/utilities.go index f30003ba09cff..845c087c02872 100644 --- a/tsc/internal/transformers/estransforms/utilities.go +++ b/tsc/internal/transformers/estransforms/utilities.go @@ -11,9 +11,9 @@ func convertClassDeclarationToClassExpression(emitContext *printer.EmitContext, updated := emitContext.Factory.NewClassExpression( transformers.ExtractModifiers(emitContext, node.Modifiers(), ^ast.ModifierFlagsExportDefault), node.Name(), - node.TypeParameters, - node.HeritageClauses, - node.Members, + node.TypeParameters(), + node.HeritageClauses(), + node.Members(), ) emitContext.SetOriginal(updated, node.AsNode()) updated.Loc = node.Loc @@ -78,7 +78,7 @@ func (s *superAccessState) visitSuperAccessNode(node *ast.Node) *ast.Node { switch node.Kind { case ast.KindCallExpression: call := node.AsCallExpression() - if ast.IsSuperProperty(call.Expression) { + if ast.IsSuperProperty(call.Expression()) { return s.substituteCallExpressionWithSuperAccess(call, s.superAccessVisitor) } return s.superAccessVisitor.VisitEachChild(node) @@ -94,7 +94,7 @@ func (s *superAccessState) visitSuperAccessNode(node *ast.Node) *ast.Node { if node.Expression().Kind == ast.KindSuperKeyword { // super[x] → _superIndex(x) or _superIndex(x).value return s.createSuperElementAccessInAsyncMethod( - node.AsElementAccessExpression().ArgumentExpression, + node.AsElementAccessExpression().ArgumentExpression(), ) } return s.superAccessVisitor.VisitEachChild(node) @@ -114,7 +114,7 @@ func (s *superAccessState) substituteSuperAccessesInBody(body *ast.Node) *ast.No // substituteCallExpressionWithSuperAccess handles super.x(args) and super[x](args). func (s *superAccessState) substituteCallExpressionWithSuperAccess(call *ast.CallExpression, visitor *ast.NodeVisitor) *ast.Node { - expression := call.Expression + expression := call.Expression() var target *ast.Node if ast.IsPropertyAccessExpression(expression) { @@ -126,7 +126,7 @@ func (s *superAccessState) substituteCallExpressionWithSuperAccess(call *ast.Cal } else if ast.IsElementAccessExpression(expression) { // super[x](args) → _superIndex(x).call(this, args) or _superIndex(x).value.call(this, args) target = s.createSuperElementAccessInAsyncMethod( - expression.AsElementAccessExpression().ArgumentExpression, + expression.AsElementAccessExpression().ArgumentExpression(), ) } else { return visitor.VisitEachChild(call.AsNode()) @@ -139,8 +139,8 @@ func (s *superAccessState) substituteCallExpressionWithSuperAccess(call *ast.Cal var allArgs []*ast.Node allArgs = append(allArgs, s.factory.NewThisExpression()) - if call.Arguments != nil { - visitedArgs := visitor.VisitNodes(call.Arguments) + if call.Arguments() != nil { + visitedArgs := visitor.VisitNodes(call.Arguments()) if visitedArgs != nil { allArgs = append(allArgs, visitedArgs.Nodes...) } @@ -262,15 +262,15 @@ func (s *superAccessState) trackSuperAccess(node *ast.Node) { s.hasSuperElementAccess = true } case ast.KindBinaryExpression: - if ast.IsAssignmentOperator(node.AsBinaryExpression().OperatorToken.Kind) && assignmentTargetContainsSuperProperty(node.AsBinaryExpression().Left) { + if ast.IsAssignmentOperator(node.AsBinaryExpression().OperatorToken().Kind) && assignmentTargetContainsSuperProperty(node.AsBinaryExpression().Left()) { s.hasSuperPropertyAssignment = true } case ast.KindPrefixUnaryExpression: - if isUpdateExpression(node) && assignmentTargetContainsSuperProperty(node.AsPrefixUnaryExpression().Operand) { + if isUpdateExpression(node) && assignmentTargetContainsSuperProperty(node.AsPrefixUnaryExpression().Operand()) { s.hasSuperPropertyAssignment = true } case ast.KindPostfixUnaryExpression: - if isUpdateExpression(node) && assignmentTargetContainsSuperProperty(node.AsPostfixUnaryExpression().Operand) { + if isUpdateExpression(node) && assignmentTargetContainsSuperProperty(node.AsPostfixUnaryExpression().Operand()) { s.hasSuperPropertyAssignment = true } } diff --git a/tsc/internal/transformers/jsxtransforms/jsx.go b/tsc/internal/transformers/jsxtransforms/jsx.go index 8a8782c497b18..7af28991dc8f9 100644 --- a/tsc/internal/transformers/jsxtransforms/jsx.go +++ b/tsc/internal/transformers/jsxtransforms/jsx.go @@ -142,7 +142,7 @@ func hasKeyAfterPropsSpread(node *ast.Node) bool { spread := false opener := node if node.Kind == ast.KindJsxElement { - opener = node.AsJsxElement().OpeningElement + opener = node.AsJsxElement().OpeningElement() } // otherwise self-closing for _, elem := range opener.Attributes().Properties() { if ast.IsJsxSpreadAttribute(elem) && (!ast.IsObjectLiteralExpression(elem.Expression()) || core.Some(elem.Expression().Properties(), ast.IsSpreadAssignment)) { @@ -283,7 +283,7 @@ func (tx *JSXTransformer) visitJsxElement(element *ast.JsxElement) *ast.Node { tagTransform = (*JSXTransformer).visitJsxOpeningLikeElementCreateElement } location := core.NewTextRange(scanner.SkipTrivia(tx.currentSourceFile.Text(), element.Pos()), element.End()) - return tagTransform(tx, element.OpeningElement, element.Children, location) + return tagTransform(tx, element.OpeningElement(), element.Children(), location) } func (tx *JSXTransformer) visitJsxSelfClosingElement(element *ast.JsxSelfClosingElement) *ast.Node { @@ -301,7 +301,7 @@ func (tx *JSXTransformer) visitJsxFragment(fragment *ast.JsxFragment) *ast.Node tagTransform = (*JSXTransformer).visitJsxOpeningFragmentCreateElement } location := core.NewTextRange(scanner.SkipTrivia(tx.currentSourceFile.Text(), fragment.Pos()), fragment.End()) - return tagTransform(tx, fragment.OpeningFragment.AsJsxOpeningFragment(), fragment.Children, location) + return tagTransform(tx, fragment.OpeningFragment().AsJsxOpeningFragment(), fragment.Children(), location) } func (tx *JSXTransformer) convertJsxChildrenToChildrenPropObject(children []*ast.JsxChild) *ast.Node { @@ -321,7 +321,7 @@ func (tx *JSXTransformer) transformJsxChildToExpression(node *ast.Node) *ast.Nod func (tx *JSXTransformer) convertJsxChildrenToChildrenPropAssignment(children []*ast.JsxChild) *ast.Node { nonWhitespceChildren := ast.GetSemanticJsxChildren(children) - if len(nonWhitespceChildren) == 1 && (nonWhitespceChildren[0].Kind != ast.KindJsxExpression || nonWhitespceChildren[0].AsJsxExpression().DotDotDotToken == nil) { + if len(nonWhitespceChildren) == 1 && (nonWhitespceChildren[0].Kind != ast.KindJsxExpression || nonWhitespceChildren[0].AsJsxExpression().DotDotDotToken() == nil) { result := tx.transformJsxChildToExpression(nonWhitespceChildren[0]) if result == nil { return nil @@ -347,14 +347,14 @@ func (tx *JSXTransformer) convertJsxChildrenToChildrenPropAssignment(children [] func (tx *JSXTransformer) getTagName(node *ast.Node) *ast.Node { if node.Kind == ast.KindJsxElement { - return tx.getTagName(node.AsJsxElement().OpeningElement) + return tx.getTagName(node.AsJsxElement().OpeningElement()) } else if ast.IsJsxOpeningLikeElement(node) { tagName := node.TagName() if ast.IsIdentifier(tagName) && scanner.IsIntrinsicJsxName(tagName.Text()) { return tx.Factory().NewStringLiteral(tagName.Text(), ast.TokenFlagsNone) } else if ast.IsJsxNamespacedName(tagName) { return tx.Factory().NewStringLiteral( - tagName.AsJsxNamespacedName().Namespace.Text()+":"+tagName.AsJsxNamespacedName().Name().Text(), ast.TokenFlagsNone, + tagName.AsJsxNamespacedName().Namespace().Text()+":"+tagName.AsJsxNamespacedName().Name().Text(), ast.TokenFlagsNone, ) } else { return tx.Factory().CreateExpressionFromEntityName(tagName) @@ -479,7 +479,7 @@ func (tx *JSXTransformer) transformJsxAttributesToProps(attrs []*ast.Node, child } func hasProto(obj *ast.ObjectLiteralExpression) bool { - for _, p := range obj.Properties.Nodes { + for _, p := range obj.Properties().Nodes { if ast.IsPropertyAssignment(p) && (ast.IsStringLiteral(p.Name()) || ast.IsIdentifier(p.Name())) && p.Name().Text() == "__proto__" { return true } @@ -488,16 +488,16 @@ func hasProto(obj *ast.ObjectLiteralExpression) bool { } func (tx *JSXTransformer) transformJsxSpreadAttributesToProps(node *ast.JsxSpreadAttribute) []*ast.Node { - if ast.IsObjectLiteralExpression(node.Expression) && !hasProto(node.Expression.AsObjectLiteralExpression()) { - res, _ := tx.Visitor().VisitSlice(node.Expression.Properties()) + if ast.IsObjectLiteralExpression(node.Expression()) && !hasProto(node.Expression().AsObjectLiteralExpression()) { + res, _ := tx.Visitor().VisitSlice(node.Expression().Properties()) return res } - return []*ast.Node{tx.Factory().NewSpreadAssignment(tx.Visitor().Visit(node.Expression))} + return []*ast.Node{tx.Factory().NewSpreadAssignment(tx.Visitor().Visit(node.Expression()))} } func (tx *JSXTransformer) transformJsxAttributeToObjectLiteralElement(node *ast.JsxAttribute) *ast.Node { name := tx.getAttributeName(node) - expression := tx.transformJsxAttributeInitializer(node.Initializer) + expression := tx.transformJsxAttributeInitializer(node.Initializer()) return tx.Factory().NewPropertyAssignment(nil, name, nil, nil, expression) } @@ -517,7 +517,7 @@ func (tx *JSXTransformer) getAttributeName(node *ast.JsxAttribute) *ast.Node { } // must be jsx namespace return tx.Factory().NewStringLiteral( - name.AsJsxNamespacedName().Namespace.Text()+":"+name.AsJsxNamespacedName().Name().Text(), ast.TokenFlagsNone, + name.AsJsxNamespacedName().Namespace().Text()+":"+name.AsJsxNamespacedName().Name().Text(), ast.TokenFlagsNone, ) } @@ -558,7 +558,7 @@ func (tx *JSXTransformer) visitJsxOpeningLikeElementOrFragmentJSX( if children != nil { nonWhitespaceChildren = ast.GetSemanticJsxChildren(children.Nodes) } - isStaticChildren := len(nonWhitespaceChildren) > 1 || (len(nonWhitespaceChildren) == 1 && ast.IsJsxExpression(nonWhitespaceChildren[0]) && nonWhitespaceChildren[0].AsJsxExpression().DotDotDotToken != nil) + isStaticChildren := len(nonWhitespaceChildren) > 1 || (len(nonWhitespaceChildren) == 1 && ast.IsJsxExpression(nonWhitespaceChildren[0]) && nonWhitespaceChildren[0].AsJsxExpression().DotDotDotToken() != nil) args := make([]*ast.Node, 0, 3) args = append(args, tagName, object) // function jsx(type, config, maybeKey) {} @@ -635,7 +635,7 @@ func (tx *JSXTransformer) createReactNamespace(reactNamespace string, parent *as // Set the parent that is in parse tree // this makes sure that parent chain is intact for checker to traverse complete scope tree - react.Parent = tx.EmitContext().ParseNode(parent) //nolint:customlint // Parent is intentionally wired to a parse-tree node for resolver traversal. + react.SetParent(tx.EmitContext().ParseNode(parent)) //nolint:customlint // Parent is intentionally wired to a parse-tree node for resolver traversal. // If the identifier refers to an exported member of a namespace, substitute with // a qualified namespace property access (e.g., `React` -> `M.React`). @@ -650,8 +650,8 @@ func (tx *JSXTransformer) createReactNamespace(reactNamespace string, parent *as func (tx *JSXTransformer) createJsxFactoryExpressionFromEntityName(e *ast.Node, parent *ast.Node) *ast.Node { if ast.IsQualifiedName(e) { - left := tx.createJsxFactoryExpressionFromEntityName(e.AsQualifiedName().Left, parent) - right := tx.Factory().NewIdentifier(e.AsQualifiedName().Right.Text()) + left := tx.createJsxFactoryExpressionFromEntityName(e.AsQualifiedName().Left(), parent) + right := tx.Factory().NewIdentifier(e.AsQualifiedName().Right().Text()) return tx.Factory().NewPropertyAccessExpression(left, nil, right, ast.NodeFlagsNone) } return tx.createReactNamespace(e.Text(), parent) @@ -850,8 +850,8 @@ func fixupWhitespaceAndDecodeEntities(text string) string { } func (tx *JSXTransformer) visitJsxExpression(expression *ast.JsxExpression) *ast.Node { - e := tx.Visitor().Visit(expression.Expression) - if expression.DotDotDotToken != nil { + e := tx.Visitor().Visit(expression.Expression()) + if expression.DotDotDotToken() != nil { return tx.Factory().NewSpreadElement(e) } return e diff --git a/tsc/internal/transformers/moduletransforms/commonjsmodule.go b/tsc/internal/transformers/moduletransforms/commonjsmodule.go index 8c479e8b68779..c78c9f20945b7 100644 --- a/tsc/internal/transformers/moduletransforms/commonjsmodule.go +++ b/tsc/internal/transformers/moduletransforms/commonjsmodule.go @@ -410,7 +410,7 @@ func (tx *CommonJSModuleTransformer) appendExportEqualsIfNeeded(statements []*as func (tx *CommonJSModuleTransformer) visitExportEquals(node *ast.ExportAssignment) *ast.Expression { grandparentNode := tx.pushNode(node.AsNode()) defer tx.popNode(grandparentNode) - return tx.Visitor().VisitNode(node.Expression) + return tx.Visitor().VisitNode(node.Expression()) } // Appends the exports of an ImportDeclaration to a statement list, returning the statement list. @@ -422,7 +422,7 @@ func (tx *CommonJSModuleTransformer) appendExportsOfImportDeclaration(statements return statements } - importClause := decl.ImportClause + importClause := decl.ImportClause() if importClause == nil { return statements } @@ -432,7 +432,7 @@ func (tx *CommonJSModuleTransformer) appendExportsOfImportDeclaration(statements statements = tx.appendExportsOfDeclaration(statements, importClause, seen, false /*liveBinding*/) } - namedBindings := importClause.AsImportClause().NamedBindings + namedBindings := importClause.AsImportClause().NamedBindings() if namedBindings != nil { switch namedBindings.Kind { case ast.KindNamespaceImport: @@ -453,7 +453,7 @@ func (tx *CommonJSModuleTransformer) appendExportsOfImportDeclaration(statements // - The `statements` parameter is a statement list to which the down-level export statements are to be appended. // - The `node` parameter is the VariableStatement whose exports are to be recorded. func (tx *CommonJSModuleTransformer) appendExportsOfVariableStatement(statements []*ast.Statement, node *ast.VariableStatement) []*ast.Statement { - return tx.appendExportsOfVariableDeclarationList(statements, node.DeclarationList.AsVariableDeclarationList() /*isForInOrOfInitializer*/, false) + return tx.appendExportsOfVariableDeclarationList(statements, node.DeclarationList().AsVariableDeclarationList() /*isForInOrOfInitializer*/, false) } // Appends the exports of a VariableDeclarationList to a statement list, returning the statement list. @@ -465,7 +465,7 @@ func (tx *CommonJSModuleTransformer) appendExportsOfVariableDeclarationList(stat return statements } - for _, decl := range node.Declarations.Nodes { + for _, decl := range node.Declarations().Nodes { statements = tx.appendExportsOfBindingElement(statements, decl, isForInOrOfInitializer) } @@ -709,7 +709,7 @@ func (tx *CommonJSModuleTransformer) getHelperExpressionForImport(node *ast.Impo } func (tx *CommonJSModuleTransformer) visitTopLevelImportDeclaration(node *ast.ImportDeclaration) *ast.Node { - if node.ImportClause == nil { + if node.ImportClause() == nil { // import "mod"; statement := tx.Factory().NewExpressionStatement(tx.createRequireCall(node.AsNode())) tx.EmitContext().SetOriginal(statement, node.AsNode()) @@ -821,14 +821,14 @@ func (tx *CommonJSModuleTransformer) visitTopLevelImportEqualsDeclaration(node * } func (tx *CommonJSModuleTransformer) visitTopLevelExportDeclaration(node *ast.ExportDeclaration) *ast.Node { - if node.ModuleSpecifier == nil { + if node.ModuleSpecifier() == nil { // Elide export declarations with no module specifier as they are handled // elsewhere. return nil } generatedName := tx.Factory().NewGeneratedNameForNode(node.AsNode()) - if node.ExportClause != nil && ast.IsNamedExports(node.ExportClause) { + if node.ExportClause() != nil && ast.IsNamedExports(node.ExportClause()) { // export { x, y } from "mod"; var statements []*ast.Statement varStatement := tx.Factory().NewVariableStatement( @@ -849,7 +849,7 @@ func (tx *CommonJSModuleTransformer) visitTopLevelExportDeclaration(node *ast.Ex tx.EmitContext().AssignCommentAndSourceMapRanges(varStatement, node.AsNode()) statements = append(statements, varStatement) - for _, specifier := range node.ExportClause.Elements() { + for _, specifier := range node.ExportClause().Elements() { specifierName := specifier.PropertyNameOrName() exportNeedsImportDefault := ast.ModuleExportNameIsDefault(specifierName) @@ -889,14 +889,14 @@ func (tx *CommonJSModuleTransformer) visitTopLevelExportDeclaration(node *ast.Ex return transformers.SingleOrMany(statements, tx.Factory()) } - if node.ExportClause != nil { + if node.ExportClause() != nil { // export * as ns from "mod"; // export * as default from "mod"; var exportName *ast.Node - if ast.IsStringLiteral(node.ExportClause.Name()) { - exportName = tx.Factory().NewStringLiteralFromNode(node.ExportClause.Name()) + if ast.IsStringLiteral(node.ExportClause().Name()) { + exportName = tx.Factory().NewStringLiteralFromNode(node.ExportClause().Name()) } else { - exportName = node.ExportClause.Name().Clone(tx.Factory()) + exportName = node.ExportClause().Name().Clone(tx.Factory()) } statement := tx.Factory().NewExpressionStatement( tx.createExportExpression( @@ -930,7 +930,7 @@ func (tx *CommonJSModuleTransformer) visitTopLevelExportAssignment(node *ast.Exp return tx.createExportStatement( tx.Factory().NewIdentifier("default"), - tx.Visitor().VisitNode(node.Expression), + tx.Visitor().VisitNode(node.Expression()), &node.Loc, /*location*/ true, /*allowComments*/ false, /*liveBinding*/ @@ -942,13 +942,13 @@ func (tx *CommonJSModuleTransformer) visitTopLevelFunctionDeclaration(node *ast. return tx.Factory().UpdateFunctionDeclaration( node, transformers.ExtractModifiers(tx.EmitContext(), node.Modifiers(), ^ast.ModifierFlagsExportDefault), - node.AsteriskToken, + node.AsteriskToken(), tx.Factory().GetDeclarationName(node.AsNode()), nil, /*typeParameters*/ - tx.Visitor().VisitNodes(node.Parameters), + tx.Visitor().VisitNodes(node.Parameters()), nil, /*type*/ nil, /*fullSignature*/ - tx.Visitor().VisitNode(node.Body), + tx.Visitor().VisitNode(node.Body()), ) } else { return tx.Visitor().VisitEachChild(node.AsNode()) @@ -963,8 +963,8 @@ func (tx *CommonJSModuleTransformer) visitTopLevelClassDeclaration(node *ast.Cla tx.Visitor().VisitModifiers(transformers.ExtractModifiers(tx.EmitContext(), node.Modifiers(), ^ast.ModifierFlagsExportDefault)), tx.Factory().GetDeclarationName(node.AsNode()), nil, /*typeParameters*/ - tx.Visitor().VisitNodes(node.HeritageClauses), - tx.Visitor().VisitNodes(node.Members), + tx.Visitor().VisitNodes(node.HeritageClauses()), + tx.Visitor().VisitNodes(node.Members()), )) } else { statements = append(statements, tx.Visitor().VisitEachChild(node.AsNode())) @@ -988,9 +988,9 @@ func (tx *CommonJSModuleTransformer) visitTopLevelVariableStatement(node *ast.Va node, modifiers, tx.Factory().UpdateVariableDeclarationList( - node.DeclarationList.AsVariableDeclarationList(), + node.DeclarationList().AsVariableDeclarationList(), variableList, - node.DeclarationList.Flags, + node.DeclarationList().Flags, ), ) if len(statements) > 0 { @@ -1024,7 +1024,7 @@ func (tx *CommonJSModuleTransformer) visitTopLevelVariableStatement(node *ast.Va } // If we're exporting these variables, then these just become assignments to 'exports.x'. - for _, variable := range node.DeclarationList.AsVariableDeclarationList().Declarations.Nodes { + for _, variable := range node.DeclarationList().AsVariableDeclarationList().Declarations().Nodes { v := variable.AsVariableDeclaration() if ast.IsIdentifier(v.Name()) && transformers.IsLocalName(tx.EmitContext(), v.Name()) { @@ -1039,7 +1039,7 @@ func (tx *CommonJSModuleTransformer) visitTopLevelVariableStatement(node *ast.Va modifiers = transformers.ExtractModifiers(tx.EmitContext(), node.Modifiers(), ^ast.ModifierFlagsExportDefault) } - if v.Initializer != nil { + if v.Initializer() != nil { variable = tx.Factory().UpdateVariableDeclaration( v, v.Name(), @@ -1047,7 +1047,7 @@ func (tx *CommonJSModuleTransformer) visitTopLevelVariableStatement(node *ast.Va nil, /*type*/ tx.createExportExpression( v.Name(), - tx.Visitor().VisitNode(v.Initializer), + tx.Visitor().VisitNode(v.Initializer()), nil, false, /*liveBinding*/ ), @@ -1055,14 +1055,14 @@ func (tx *CommonJSModuleTransformer) visitTopLevelVariableStatement(node *ast.Va } pushVariable(variable) - } else if v.Initializer != nil && !ast.IsBindingPattern(v.Name()) && (ast.IsArrowFunction(v.Initializer) || ast.IsFunctionExpression(v.Initializer) || ast.IsClassExpression(v.Initializer)) { + } else if v.Initializer() != nil && !ast.IsBindingPattern(v.Name()) && (ast.IsArrowFunction(v.Initializer()) || ast.IsFunctionExpression(v.Initializer()) || ast.IsClassExpression(v.Initializer())) { // preserve variable declarations for functions and classes to assign names pushVariable(tx.Factory().NewVariableDeclaration( v.Name(), - v.ExclamationToken, - v.Type, - tx.Visitor().VisitNode(v.Initializer), + v.ExclamationToken(), + v.Type(), + tx.Visitor().VisitNode(v.Initializer()), )) propertyAccess := tx.Factory().NewPropertyAccessExpression( @@ -1108,7 +1108,7 @@ func (tx *CommonJSModuleTransformer) visitTopLevelVariableStatement(node *ast.Va } func (tx *CommonJSModuleTransformer) transformInitializedVariable(node *ast.VariableDeclaration) *ast.Expression { - if node.Initializer == nil { + if node.Initializer() == nil { return nil } name := node.Name() @@ -1131,7 +1131,7 @@ func (tx *CommonJSModuleTransformer) transformInitializedVariable(node *ast.Vari ast.NodeFlagsNone, ) tx.EmitContext().AssignCommentAndSourceMapRanges(propertyAccess, name) - return tx.Factory().NewAssignmentExpression(propertyAccess, node.Initializer) + return tx.Factory().NewAssignmentExpression(propertyAccess, node.Initializer()) } // Visits a top-level nested variable statement as it may contain `var` declarations that are hoisted and may still be @@ -1146,8 +1146,8 @@ func (tx *CommonJSModuleTransformer) visitTopLevelNestedVariableStatement(node * // Visits a top-level nested `for` statement as it may contain `var` declarations that are hoisted and may still be // exported with `export {}`. func (tx *CommonJSModuleTransformer) visitTopLevelNestedForStatement(node *ast.ForStatement) *ast.Node { - if node.Initializer != nil && ast.IsVariableDeclarationList(node.Initializer) && node.Initializer.Flags&ast.NodeFlagsBlockScoped == 0 { - exportStatements := tx.appendExportsOfVariableDeclarationList(nil /*statements*/, node.Initializer.AsVariableDeclarationList(), false /*isForInOrOfInitializer*/) + if node.Initializer() != nil && ast.IsVariableDeclarationList(node.Initializer()) && node.Initializer().Flags&ast.NodeFlagsBlockScoped == 0 { + exportStatements := tx.appendExportsOfVariableDeclarationList(nil /*statements*/, node.Initializer().AsVariableDeclarationList(), false /*isForInOrOfInitializer*/) if len(exportStatements) > 0 { // given: // export { x } @@ -1158,14 +1158,14 @@ func (tx *CommonJSModuleTransformer) visitTopLevelNestedForStatement(node *ast.F // for (; ;) { } var statements []*ast.Statement - varDeclList := tx.discardedValueVisitor.VisitNode(node.Initializer) + varDeclList := tx.discardedValueVisitor.VisitNode(node.Initializer()) varStatement := tx.Factory().NewVariableStatement(nil /*modifiers*/, varDeclList) statements = append(statements, varStatement) statements = append(statements, exportStatements...) - condition := tx.Visitor().VisitNode(node.Condition) - incrementor := tx.discardedValueVisitor.VisitNode(node.Incrementor) - body := tx.EmitContext().VisitIterationBody(node.Statement, tx.topLevelNestedVisitor) + condition := tx.Visitor().VisitNode(node.Condition()) + incrementor := tx.discardedValueVisitor.VisitNode(node.Incrementor()) + body := tx.EmitContext().VisitIterationBody(node.Statement(), tx.topLevelNestedVisitor) statements = append(statements, tx.Factory().UpdateForStatement( node, nil, /*initializer*/ @@ -1178,18 +1178,18 @@ func (tx *CommonJSModuleTransformer) visitTopLevelNestedForStatement(node *ast.F } return tx.Factory().UpdateForStatement( node, - tx.discardedValueVisitor.VisitNode(node.Initializer), - tx.Visitor().VisitNode(node.Condition), - tx.discardedValueVisitor.VisitNode(node.Incrementor), - tx.EmitContext().VisitIterationBody(node.Statement, tx.topLevelNestedVisitor), + tx.discardedValueVisitor.VisitNode(node.Initializer()), + tx.Visitor().VisitNode(node.Condition()), + tx.discardedValueVisitor.VisitNode(node.Incrementor()), + tx.EmitContext().VisitIterationBody(node.Statement(), tx.topLevelNestedVisitor), ) } // Visits a top-level nested `for..in` or `for..of` statement as it may contain `var` declarations that are hoisted and // may still be exported with `export {}`. func (tx *CommonJSModuleTransformer) visitTopLevelNestedForInOrOfStatement(node *ast.ForInOrOfStatement) *ast.Node { - if ast.IsVariableDeclarationList(node.Initializer) && node.Initializer.Flags&ast.NodeFlagsBlockScoped == 0 { - exportStatements := tx.appendExportsOfVariableDeclarationList(nil /*statements*/, node.Initializer.AsVariableDeclarationList(), true /*isForInOrOfInitializer*/) + if ast.IsVariableDeclarationList(node.Initializer()) && node.Initializer().Flags&ast.NodeFlagsBlockScoped == 0 { + exportStatements := tx.appendExportsOfVariableDeclarationList(nil /*statements*/, node.Initializer().AsVariableDeclarationList(), true /*isForInOrOfInitializer*/) if len(exportStatements) > 0 { // given: // export { x } @@ -1202,28 +1202,28 @@ func (tx *CommonJSModuleTransformer) visitTopLevelNestedForInOrOfStatement(node // ... // } - initializer := tx.discardedValueVisitor.VisitNode(node.Initializer) - expression := tx.Visitor().VisitNode(node.Expression) - body := tx.EmitContext().VisitIterationBody(node.Statement, tx.topLevelNestedVisitor) + initializer := tx.discardedValueVisitor.VisitNode(node.Initializer()) + expression := tx.Visitor().VisitNode(node.Expression()) + body := tx.EmitContext().VisitIterationBody(node.Statement(), tx.topLevelNestedVisitor) if ast.IsBlock(body) { block := body.AsBlock() - bodyStatements := append(exportStatements, block.Statements.Nodes...) + bodyStatements := append(exportStatements, block.Statements().Nodes...) bodyStatementList := tx.Factory().NewNodeList(bodyStatements) - bodyStatementList.Loc = block.Statements.Loc + bodyStatementList.Loc = block.Statements().Loc body = tx.Factory().UpdateBlock(block, bodyStatementList, block.MultiLine) } else { bodyStatements := append(exportStatements, body) body = tx.Factory().NewBlock(tx.Factory().NewNodeList(bodyStatements), true /*multiLine*/) } - return tx.Factory().UpdateForInOrOfStatement(node, node.AwaitModifier, initializer, expression, body) + return tx.Factory().UpdateForInOrOfStatement(node, node.AwaitModifier(), initializer, expression, body) } } return tx.Factory().UpdateForInOrOfStatement( node, - node.AwaitModifier, - tx.discardedValueVisitor.VisitNode(node.Initializer), - tx.Visitor().VisitNode(node.Expression), - tx.EmitContext().VisitIterationBody(node.Statement, tx.topLevelNestedVisitor), + node.AwaitModifier(), + tx.discardedValueVisitor.VisitNode(node.Initializer()), + tx.Visitor().VisitNode(node.Expression()), + tx.EmitContext().VisitIterationBody(node.Statement(), tx.topLevelNestedVisitor), ) } @@ -1232,8 +1232,8 @@ func (tx *CommonJSModuleTransformer) visitTopLevelNestedForInOrOfStatement(node func (tx *CommonJSModuleTransformer) visitTopLevelNestedDoStatement(node *ast.DoStatement) *ast.Node { return tx.Factory().UpdateDoStatement( node, - tx.EmitContext().VisitIterationBody(node.Statement, tx.topLevelNestedVisitor), - tx.Visitor().VisitNode(node.Expression), + tx.EmitContext().VisitIterationBody(node.Statement(), tx.topLevelNestedVisitor), + tx.Visitor().VisitNode(node.Expression()), ) } @@ -1242,31 +1242,31 @@ func (tx *CommonJSModuleTransformer) visitTopLevelNestedDoStatement(node *ast.Do func (tx *CommonJSModuleTransformer) visitTopLevelNestedWhileStatement(node *ast.WhileStatement) *ast.Node { return tx.Factory().UpdateWhileStatement( node, - tx.Visitor().VisitNode(node.Expression), - tx.EmitContext().VisitIterationBody(node.Statement, tx.topLevelNestedVisitor), + tx.Visitor().VisitNode(node.Expression()), + tx.EmitContext().VisitIterationBody(node.Statement(), tx.topLevelNestedVisitor), ) } // Visits a top-level nested labeled statement as it may contain `var` declarations that are hoisted and may still be // exported with `export {}`. func (tx *CommonJSModuleTransformer) visitTopLevelNestedLabeledStatement(node *ast.LabeledStatement) *ast.Node { - statement := tx.topLevelNestedVisitor.VisitEmbeddedStatement(node.Statement) + statement := tx.topLevelNestedVisitor.VisitEmbeddedStatement(node.Statement()) if statement == nil { statement = tx.Factory().NewEmptyStatement() } - return tx.Factory().UpdateLabeledStatement(node, node.Label, statement) + return tx.Factory().UpdateLabeledStatement(node, node.Label(), statement) } // Visits a top-level nested `with` statement as it may contain `var` declarations that are hoisted and may still be // exported with `export {}`. func (tx *CommonJSModuleTransformer) visitTopLevelNestedWithStatement(node *ast.WithStatement) *ast.Node { - statement := tx.topLevelNestedVisitor.VisitEmbeddedStatement(node.Statement) + statement := tx.topLevelNestedVisitor.VisitEmbeddedStatement(node.Statement()) if statement == nil { statement = tx.Factory().NewEmptyStatement() } return tx.Factory().UpdateWithStatement( node, - tx.Visitor().VisitNode(node.Expression), + tx.Visitor().VisitNode(node.Expression()), statement, ) } @@ -1274,12 +1274,12 @@ func (tx *CommonJSModuleTransformer) visitTopLevelNestedWithStatement(node *ast. // Visits a top-level nested `if` statement as it may contain `var` declarations that are hoisted and may still be // exported with `export {}`. func (tx *CommonJSModuleTransformer) visitTopLevelNestedIfStatement(node *ast.IfStatement) *ast.Node { - expression := tx.Visitor().VisitNode(node.Expression) - thenStatement := tx.topLevelNestedVisitor.VisitEmbeddedStatement(node.ThenStatement) + expression := tx.Visitor().VisitNode(node.Expression()) + thenStatement := tx.topLevelNestedVisitor.VisitEmbeddedStatement(node.ThenStatement()) if thenStatement == nil { thenStatement = tx.Factory().NewBlock(tx.Factory().NewNodeList(nil), false /*multiLine*/) } - elseStatement := tx.topLevelNestedVisitor.VisitEmbeddedStatement(node.ElseStatement) + elseStatement := tx.topLevelNestedVisitor.VisitEmbeddedStatement(node.ElseStatement()) return tx.Factory().UpdateIfStatement(node, expression, thenStatement, elseStatement) } @@ -1288,8 +1288,8 @@ func (tx *CommonJSModuleTransformer) visitTopLevelNestedIfStatement(node *ast.If func (tx *CommonJSModuleTransformer) visitTopLevelNestedSwitchStatement(node *ast.SwitchStatement) *ast.Node { return tx.Factory().UpdateSwitchStatement( node, - tx.Visitor().VisitNode(node.Expression), - tx.topLevelNestedVisitor.VisitNode(node.CaseBlock), + tx.Visitor().VisitNode(node.Expression()), + tx.topLevelNestedVisitor.VisitNode(node.CaseBlock()), ) } @@ -1304,8 +1304,8 @@ func (tx *CommonJSModuleTransformer) visitTopLevelNestedCaseBlock(node *ast.Case func (tx *CommonJSModuleTransformer) visitTopLevelNestedCaseOrDefaultClause(node *ast.CaseOrDefaultClause) *ast.Node { return tx.Factory().UpdateCaseOrDefaultClause( node, - tx.Visitor().VisitNode(node.Expression), - tx.topLevelNestedVisitor.VisitNodes(node.Statements), + tx.Visitor().VisitNode(node.Expression()), + tx.topLevelNestedVisitor.VisitNodes(node.Statements()), ) } @@ -1320,8 +1320,8 @@ func (tx *CommonJSModuleTransformer) visitTopLevelNestedTryStatement(node *ast.T func (tx *CommonJSModuleTransformer) visitTopLevelNestedCatchClause(node *ast.CatchClause) *ast.Node { return tx.Factory().UpdateCatchClause( node, - node.VariableDeclaration, - tx.topLevelNestedVisitor.VisitNode(node.Block), + node.VariableDeclaration(), + tx.topLevelNestedVisitor.VisitNode(node.Block()), ) } @@ -1334,20 +1334,20 @@ func (tx *CommonJSModuleTransformer) visitTopLevelNestedBlock(node *ast.Block) * func (tx *CommonJSModuleTransformer) visitForStatement(node *ast.ForStatement) *ast.Node { return tx.Factory().UpdateForStatement( node, - tx.discardedValueVisitor.VisitNode(node.Initializer), - tx.Visitor().VisitNode(node.Condition), - tx.discardedValueVisitor.VisitNode(node.Incrementor), - tx.EmitContext().VisitIterationBody(node.Statement, tx.topLevelNestedVisitor), + tx.discardedValueVisitor.VisitNode(node.Initializer()), + tx.Visitor().VisitNode(node.Condition()), + tx.discardedValueVisitor.VisitNode(node.Incrementor()), + tx.EmitContext().VisitIterationBody(node.Statement(), tx.topLevelNestedVisitor), ) } func (tx *CommonJSModuleTransformer) visitForInOrOfStatement(node *ast.ForInOrOfStatement) *ast.Node { return tx.Factory().UpdateForInOrOfStatement( node, - node.AwaitModifier, - tx.discardedValueVisitor.VisitNode(node.Initializer), - tx.Visitor().VisitNode(node.Expression), - tx.EmitContext().VisitIterationBody(node.Statement, tx.topLevelNestedVisitor), + node.AwaitModifier(), + tx.discardedValueVisitor.VisitNode(node.Initializer()), + tx.Visitor().VisitNode(node.Expression()), + tx.EmitContext().VisitIterationBody(node.Statement(), tx.topLevelNestedVisitor), ) } @@ -1363,13 +1363,13 @@ func (tx *CommonJSModuleTransformer) visitVoidExpression(node *ast.VoidExpressio // Visits a parenthesized expression whose value may be discarded at runtime. func (tx *CommonJSModuleTransformer) visitParenthesizedExpression(node *ast.ParenthesizedExpression, resultIsDiscarded bool) *ast.Node { - expression := core.IfElse(resultIsDiscarded, tx.discardedValueVisitor, tx.Visitor()).VisitNode(node.Expression) + expression := core.IfElse(resultIsDiscarded, tx.discardedValueVisitor, tx.Visitor()).VisitNode(node.Expression()) return tx.Factory().UpdateParenthesizedExpression(node, expression) } // Visits a partially emitted expression whose value may be discarded at runtime. func (tx *CommonJSModuleTransformer) visitPartiallyEmittedExpression(node *ast.PartiallyEmittedExpression, resultIsDiscarded bool) *ast.Node { - expression := core.IfElse(resultIsDiscarded, tx.discardedValueVisitor, tx.Visitor()).VisitNode(node.Expression) + expression := core.IfElse(resultIsDiscarded, tx.discardedValueVisitor, tx.Visitor()).VisitNode(node.Expression()) return tx.Factory().UpdatePartiallyEmittedExpression(node, expression) } @@ -1398,10 +1398,10 @@ func (tx *CommonJSModuleTransformer) visitAssignmentExpression(node *ast.BinaryE // - We do not transform generated identifiers unless they are file-level reserved names. // - We do not transform identifiers tagged with the LocalName flag. // - We only transform identifiers that are exported at the top level. - if ast.IsIdentifier(node.Left) && - (!transformers.IsGeneratedIdentifier(tx.EmitContext(), node.Left) || isFileLevelReservedGeneratedIdentifier(tx.EmitContext(), node.Left)) && - !transformers.IsLocalName(tx.EmitContext(), node.Left) { - exportedNames := tx.getExports(node.Left) + if ast.IsIdentifier(node.Left()) && + (!transformers.IsGeneratedIdentifier(tx.EmitContext(), node.Left()) || isFileLevelReservedGeneratedIdentifier(tx.EmitContext(), node.Left())) && + !transformers.IsLocalName(tx.EmitContext(), node.Left()) { + exportedNames := tx.getExports(node.Left()) if len(exportedNames) > 0 { // For each additional export of the declaration, apply an export assignment. expression := tx.Visitor().VisitEachChild(node.AsNode()) @@ -1417,7 +1417,7 @@ func (tx *CommonJSModuleTransformer) visitAssignmentExpression(node *ast.BinaryE // Visits a destructuring assignment which might target an exported identifier. func (tx *CommonJSModuleTransformer) visitDestructuringAssignment(node *ast.BinaryExpression, valueIsDiscarded bool) *ast.Node { - if tx.destructuringNeedsFlattening(node.Left) { + if tx.destructuringNeedsFlattening(node.Left()) { return transformers.FlattenDestructuringAssignment( &tx.Transformer, node.AsNode(), @@ -1452,7 +1452,7 @@ func (tx *CommonJSModuleTransformer) destructuringNeedsFlattening(node *ast.Node } } } else if ast.IsArrayLiteralExpression(node) { - for _, elem := range node.AsArrayLiteralExpression().Elements.Nodes { + for _, elem := range node.AsArrayLiteralExpression().Elements().Nodes { if ast.IsSpreadElement(elem) { if tx.destructuringNeedsFlattening(elem.Expression()) { return true @@ -1547,7 +1547,7 @@ func (tx *CommonJSModuleTransformer) visitAssignmentProperty(node *ast.PropertyA tx.Visitor().VisitNode(node.Name()), nil, /*postfixToken*/ nil, /*typeNode*/ - tx.assignmentPatternVisitor.VisitNode(node.Initializer), + tx.assignmentPatternVisitor.VisitNode(node.Initializer()), ) } @@ -1560,12 +1560,12 @@ func (tx *CommonJSModuleTransformer) visitShorthandAssignmentProperty(node *ast. target, nil, /*postfixToken*/ nil, /*typeNode*/ - node.EqualsToken, - tx.Visitor().VisitNode(node.ObjectAssignmentInitializer), + node.EqualsToken(), + tx.Visitor().VisitNode(node.ObjectAssignmentInitializer()), ) } - if node.ObjectAssignmentInitializer != nil { - equalsToken := node.EqualsToken + if node.ObjectAssignmentInitializer() != nil { + equalsToken := node.EqualsToken() if equalsToken == nil { equalsToken = tx.Factory().NewToken(ast.KindEqualsToken) } @@ -1574,7 +1574,7 @@ func (tx *CommonJSModuleTransformer) visitShorthandAssignmentProperty(node *ast. target, nil, /*typeNode*/ equalsToken, - tx.Visitor().VisitNode(node.ObjectAssignmentInitializer), + tx.Visitor().VisitNode(node.ObjectAssignmentInitializer()), ) } updated := tx.Factory().NewPropertyAssignment( @@ -1592,28 +1592,28 @@ func (tx *CommonJSModuleTransformer) visitShorthandAssignmentProperty(node *ast. func (tx *CommonJSModuleTransformer) visitAssignmentRestProperty(node *ast.SpreadAssignment) *ast.Node { return tx.Factory().UpdateSpreadAssignment( node, - tx.visitDestructuringAssignmentTarget(node.Expression), + tx.visitDestructuringAssignmentTarget(node.Expression()), ) } func (tx *CommonJSModuleTransformer) visitAssignmentRestElement(node *ast.SpreadElement) *ast.Node { return tx.Factory().UpdateSpreadElement( node, - tx.visitDestructuringAssignmentTarget(node.Expression), + tx.visitDestructuringAssignmentTarget(node.Expression()), ) } func (tx *CommonJSModuleTransformer) visitAssignmentElement(node *ast.Node) *ast.Node { if ast.IsBinaryExpression(node) { n := node.AsBinaryExpression() - if n.OperatorToken.Kind == ast.KindEqualsToken { + if n.OperatorToken().Kind == ast.KindEqualsToken { return tx.Factory().UpdateBinaryExpression( n, nil, /*modifiers*/ - tx.visitDestructuringAssignmentTarget(n.Left), + tx.visitDestructuringAssignmentTarget(n.Left()), nil, /*typeNode*/ - n.OperatorToken, - tx.Visitor().VisitNode(n.Right), + n.OperatorToken(), + tx.Visitor().VisitNode(n.Right()), ) } } @@ -1688,9 +1688,9 @@ func (tx *CommonJSModuleTransformer) visitDestructuringAssignmentTargetNoStack(n // Visits a comma expression whose left-hand value is always discard, and whose right-hand value may be discarded at runtime. func (tx *CommonJSModuleTransformer) visitCommaExpression(node *ast.BinaryExpression, resultIsDiscarded bool) *ast.Node { - left := tx.discardedValueVisitor.VisitNode(node.Left) - right := core.IfElse(resultIsDiscarded, tx.discardedValueVisitor, tx.Visitor()).VisitNode(node.Right) - return tx.Factory().UpdateBinaryExpression(node, nil /*modifiers*/, left, nil /*typeNode*/, node.OperatorToken, right) + left := tx.discardedValueVisitor.VisitNode(node.Left()) + right := core.IfElse(resultIsDiscarded, tx.discardedValueVisitor, tx.Visitor()).VisitNode(node.Right()) + return tx.Factory().UpdateBinaryExpression(node, nil /*modifiers*/, left, nil /*typeNode*/, node.OperatorToken(), right) } // Visits a prefix unary expression that might modify an exported identifier. @@ -1705,9 +1705,9 @@ func (tx *CommonJSModuleTransformer) visitPrefixUnaryExpression(node *ast.Prefix // namespace due to how they are transformed in TypeScript. // - We only transform identifiers that are exported at the top level. if (node.Operator == ast.KindPlusPlusToken || node.Operator == ast.KindMinusMinusToken) && - ast.IsIdentifier(node.Operand) && - !transformers.IsLocalName(tx.EmitContext(), node.Operand) { - exportedNames := tx.getExports(node.Operand) + ast.IsIdentifier(node.Operand()) && + !transformers.IsLocalName(tx.EmitContext(), node.Operand()) { + exportedNames := tx.getExports(node.Operand()) if len(exportedNames) > 0 { // given: // var x = 0; @@ -1720,7 +1720,7 @@ func (tx *CommonJSModuleTransformer) visitPrefixUnaryExpression(node *ast.Prefix // note: // after the operation, `exports.x` will hold the value of `x` after the increment. - expression := tx.Factory().UpdatePrefixUnaryExpression(node, node.Operator, tx.Visitor().VisitNode(node.Operand)) + expression := tx.Factory().UpdatePrefixUnaryExpression(node, node.Operator, tx.Visitor().VisitNode(node.Operand())) for _, exportName := range exportedNames { expression = tx.createExportExpression(exportName, expression, nil /*location*/, false /*liveBinding*/) tx.EmitContext().AssignCommentAndSourceMapRanges(expression, node.AsNode()) @@ -1743,9 +1743,9 @@ func (tx *CommonJSModuleTransformer) visitPostfixUnaryExpression(node *ast.Postf // namespace due to how they are transformed in TypeScript. // - We only transform identifiers that are exported at the top level. if (node.Operator == ast.KindPlusPlusToken || node.Operator == ast.KindMinusMinusToken) && - ast.IsIdentifier(node.Operand) && - !transformers.IsLocalName(tx.EmitContext(), node.Operand) { - exportedNames := tx.getExports(node.Operand) + ast.IsIdentifier(node.Operand()) && + !transformers.IsLocalName(tx.EmitContext(), node.Operand()) { + exportedNames := tx.getExports(node.Operand()) if len(exportedNames) > 0 { // given (value is discarded): // var x = 0; @@ -1772,7 +1772,7 @@ func (tx *CommonJSModuleTransformer) visitPostfixUnaryExpression(node *ast.Postf // `y` will hold the value of `x` before the increment. var temp *ast.IdentifierNode - expression := tx.Factory().UpdatePostfixUnaryExpression(node, tx.Visitor().VisitNode(node.Operand), node.Operator) + expression := tx.Factory().UpdatePostfixUnaryExpression(node, tx.Visitor().VisitNode(node.Operand()), node.Operator) if !resultIsDiscarded { temp = tx.Factory().NewTempVariable() tx.EmitContext().AddVariableDeclaration(temp) @@ -1781,7 +1781,7 @@ func (tx *CommonJSModuleTransformer) visitPostfixUnaryExpression(node *ast.Postf tx.EmitContext().AssignCommentAndSourceMapRanges(expression, node.AsNode()) } - expression = tx.Factory().NewCommaExpression(expression, node.Operand.Clone(tx.Factory())) + expression = tx.Factory().NewCommaExpression(expression, node.Operand().Clone(tx.Factory())) tx.EmitContext().AssignCommentAndSourceMapRanges(expression, node.AsNode()) for _, exportName := range exportedNames { @@ -1806,18 +1806,18 @@ func (tx *CommonJSModuleTransformer) visitPostfixUnaryExpression(node *ast.Postf func (tx *CommonJSModuleTransformer) visitCallExpression(node *ast.CallExpression) *ast.Node { needsRewrite := false if tx.compilerOptions.RewriteRelativeImportExtensions.IsTrue() { - if ast.IsImportCall(node.AsNode()) && len(node.Arguments.Nodes) > 0 || + if ast.IsImportCall(node.AsNode()) && len(node.Arguments().Nodes) > 0 || ast.IsInJSFile(node.AsNode()) && ast.IsRequireCall(node.AsNode(), false /*requireStringLiteralLikeArgument*/) { needsRewrite = true } } - if node.Expression.Kind == ast.KindImportKeyword && tx.shouldTransformImportCall() { + if node.Expression().Kind == ast.KindImportKeyword && tx.shouldTransformImportCall() { return tx.visitImportCallExpression(node, needsRewrite) } if needsRewrite { return tx.shimOrRewriteImportOrRequireCall(node.AsCallExpression()) } - if ast.IsIdentifier(node.Expression) { + if ast.IsIdentifier(node.Expression()) { // given: // import { f } from "mod"; // f(); @@ -1826,16 +1826,16 @@ func (tx *CommonJSModuleTransformer) visitCallExpression(node *ast.CallExpressio // (0, mod_1.f)(); // note: // the indirect call is applied by the printer by way of the `EFIndirectCall` emit flag. - expression := tx.visitExpressionIdentifier(node.Expression) + expression := tx.visitExpressionIdentifier(node.Expression()) updated := tx.Factory().UpdateCallExpression( node, expression, - node.QuestionDotToken, + node.QuestionDotToken(), nil, /*typeArguments*/ - tx.Visitor().VisitNodes(node.Arguments), + tx.Visitor().VisitNodes(node.Arguments()), node.Flags, ) - if !ast.IsIdentifier(expression) && !transformers.IsHelperName(tx.EmitContext(), node.Expression) { + if !ast.IsIdentifier(expression) && !transformers.IsHelperName(tx.EmitContext(), node.Expression()) { tx.EmitContext().AddEmitFlags(updated, printer.EFIndirectCall) } return updated @@ -1853,7 +1853,7 @@ func (tx *CommonJSModuleTransformer) visitImportCallExpression(node *ast.CallExp } externalModuleName := getExternalModuleNameLiteral(tx.Factory(), node.AsNode(), tx.currentSourceFile, nil /*host*/, nil /*resolver*/, tx.compilerOptions) - firstArgument := tx.Visitor().VisitNode(core.FirstOrNil(node.Arguments.Nodes)) + firstArgument := tx.Visitor().VisitNode(core.FirstOrNil(node.Arguments().Nodes)) // Only use the external module name if it differs from the first argument. This allows us to preserve the quote style of the argument on output. var argument *ast.Expression @@ -1965,10 +1965,10 @@ func (tx *CommonJSModuleTransformer) createImportCallExpressionCommonJS(arg *ast } func (tx *CommonJSModuleTransformer) shimOrRewriteImportOrRequireCall(node *ast.CallExpression) *ast.Node { - expression := tx.Visitor().VisitNode(node.Expression) - argumentsList := node.Arguments - if len(node.Arguments.Nodes) > 0 { - firstArgument := tx.Visitor().VisitNode(node.Arguments.Nodes[0]) + expression := tx.Visitor().VisitNode(node.Expression()) + argumentsList := node.Arguments() + if len(node.Arguments().Nodes) > 0 { + firstArgument := tx.Visitor().VisitNode(node.Arguments().Nodes[0]) firstArgumentChanged := false if ast.IsStringLiteralLike(firstArgument) { rewritten := rewriteModuleSpecifier(tx.EmitContext(), firstArgument, tx.compilerOptions) @@ -1979,18 +1979,18 @@ func (tx *CommonJSModuleTransformer) shimOrRewriteImportOrRequireCall(node *ast. firstArgumentChanged = true } - rest, restChanged := tx.Visitor().VisitSlice(node.Arguments.Nodes[1:]) + rest, restChanged := tx.Visitor().VisitSlice(node.Arguments().Nodes[1:]) if firstArgumentChanged || restChanged { arguments := append([]*ast.Expression{firstArgument}, rest...) argumentsList = tx.Factory().NewNodeList(arguments) - argumentsList.Loc = node.Arguments.Loc + argumentsList.Loc = node.Arguments().Loc } } return tx.Factory().UpdateCallExpression( node, expression, - node.QuestionDotToken, + node.QuestionDotToken(), nil, /*typeArguments*/ argumentsList, node.Flags, @@ -1999,7 +1999,7 @@ func (tx *CommonJSModuleTransformer) shimOrRewriteImportOrRequireCall(node *ast. // Visits a tagged template expression that might reference an imported symbol and thus require an indirect call. func (tx *CommonJSModuleTransformer) visitTaggedTemplateExpression(node *ast.TaggedTemplateExpression) *ast.Node { - if ast.IsIdentifier(node.Tag) { + if ast.IsIdentifier(node.Tag()) { // given: // import { f } from "mod"; // f``; @@ -2009,16 +2009,16 @@ func (tx *CommonJSModuleTransformer) visitTaggedTemplateExpression(node *ast.Tag // note: // the indirect call is applied by the printer by way of the `EFIndirectCall` emit flag. - expression := tx.visitExpressionIdentifier(node.Tag) + expression := tx.visitExpressionIdentifier(node.Tag()) updated := tx.Factory().UpdateTaggedTemplateExpression( node, expression, nil, /*questionDotToken*/ nil, /*typeArguments*/ - tx.Visitor().VisitNode(node.Template), + tx.Visitor().VisitNode(node.Template()), node.Flags, ) - if !ast.IsIdentifier(expression) && !transformers.IsHelperName(tx.EmitContext(), node.Tag) { + if !ast.IsIdentifier(expression) && !transformers.IsHelperName(tx.EmitContext(), node.Tag()) { tx.EmitContext().AddEmitFlags(updated, printer.EFIndirectCall) } return updated @@ -2034,10 +2034,10 @@ func (tx *CommonJSModuleTransformer) visitShorthandPropertyAssignment(node *ast. // A shorthand property with an assignment initializer is probably part of a // destructuring assignment expression := exportedOrImportedName - if node.ObjectAssignmentInitializer != nil { + if node.ObjectAssignmentInitializer() != nil { expression = tx.Factory().NewAssignmentExpression( expression, - tx.Visitor().VisitNode(node.ObjectAssignmentInitializer), + tx.Visitor().VisitNode(node.ObjectAssignmentInitializer()), ) } assignment := tx.Factory().NewPropertyAssignment(nil /*modifiers*/, name, nil /*postfixToken*/, nil /*typeNode*/, expression) @@ -2051,8 +2051,8 @@ func (tx *CommonJSModuleTransformer) visitShorthandPropertyAssignment(node *ast. exportedOrImportedName, nil, /*postfixToken*/ nil, /*typeNode*/ - node.EqualsToken, - tx.Visitor().VisitNode(node.ObjectAssignmentInitializer), + node.EqualsToken(), + tx.Visitor().VisitNode(node.ObjectAssignmentInitializer()), ) } @@ -2087,7 +2087,7 @@ func (tx *CommonJSModuleTransformer) visitExpressionIdentifier(node *ast.Identif if importDeclaration != nil { if ast.IsImportClause(importDeclaration) { reference := tx.Factory().NewPropertyAccessExpression( - tx.Factory().NewGeneratedNameForNode(importDeclaration.Parent), //nolint:customlint // Resolver returns parse-tree declarations; Parent is used to find the owning import declaration. + tx.Factory().NewGeneratedNameForNode(importDeclaration.Parent()), //nolint:customlint // Resolver returns parse-tree declarations; Parent is used to find the owning import declaration. nil, /*questionDotToken*/ tx.Factory().NewIdentifier("default"), ast.NodeFlagsNone, diff --git a/tsc/internal/transformers/moduletransforms/esmodule.go b/tsc/internal/transformers/moduletransforms/esmodule.go index 87f20beb2033d..0dc7dc0c2759b 100644 --- a/tsc/internal/transformers/moduletransforms/esmodule.go +++ b/tsc/internal/transformers/moduletransforms/esmodule.go @@ -104,13 +104,13 @@ func (tx *ESModuleTransformer) visitImportDeclaration(node *ast.ImportDeclaratio if !tx.compilerOptions.RewriteRelativeImportExtensions.IsTrue() { return node.AsNode() } - updatedModuleSpecifier := rewriteModuleSpecifier(tx.EmitContext(), node.ModuleSpecifier, tx.compilerOptions) + updatedModuleSpecifier := rewriteModuleSpecifier(tx.EmitContext(), node.ModuleSpecifier(), tx.compilerOptions) return tx.Factory().UpdateImportDeclaration( node, nil, /*modifiers*/ - tx.Visitor().VisitNode(node.ImportClause), + tx.Visitor().VisitNode(node.ImportClause()), updatedModuleSpecifier, - tx.Visitor().VisitNode(node.Attributes), + tx.Visitor().VisitNode(node.Attributes()), ) } @@ -186,7 +186,7 @@ func (tx *ESModuleTransformer) visitExportAssignment(node *ast.ExportAssignment) tx.Factory().NewIdentifier("exports"), ast.NodeFlagsNone, ), - tx.Visitor().VisitNode(node.Expression), + tx.Visitor().VisitNode(node.Expression()), ), ) tx.EmitContext().SetOriginal(statement, node.AsNode()) @@ -194,24 +194,24 @@ func (tx *ESModuleTransformer) visitExportAssignment(node *ast.ExportAssignment) } func (tx *ESModuleTransformer) visitExportDeclaration(node *ast.ExportDeclaration) *ast.Node { - if node.ModuleSpecifier == nil { + if node.ModuleSpecifier() == nil { return node.AsNode() } - updatedModuleSpecifier := rewriteModuleSpecifier(tx.EmitContext(), node.ModuleSpecifier, tx.compilerOptions) - if tx.compilerOptions.Module > core.ModuleKindES2015 || node.ExportClause == nil || !ast.IsNamespaceExport(node.ExportClause) { + updatedModuleSpecifier := rewriteModuleSpecifier(tx.EmitContext(), node.ModuleSpecifier(), tx.compilerOptions) + if tx.compilerOptions.Module > core.ModuleKindES2015 || node.ExportClause() == nil || !ast.IsNamespaceExport(node.ExportClause()) { // Either ill-formed or don't need to be transformed. return tx.Factory().UpdateExportDeclaration( node, nil, /*modifiers*/ false, /*isTypeOnly*/ - node.ExportClause, + node.ExportClause(), updatedModuleSpecifier, - tx.Visitor().VisitNode(node.Attributes), + tx.Visitor().VisitNode(node.Attributes()), ) } - oldIdentifier := node.ExportClause.Name() + oldIdentifier := node.ExportClause().Name() synthName := tx.Factory().NewGeneratedNameForNode(oldIdentifier) importDecl := tx.Factory().NewImportDeclaration( nil, /*modifiers*/ @@ -221,9 +221,9 @@ func (tx *ESModuleTransformer) visitExportDeclaration(node *ast.ExportDeclaratio tx.Factory().NewNamespaceImport(synthName), ), updatedModuleSpecifier, - tx.Visitor().VisitNode(node.Attributes), + tx.Visitor().VisitNode(node.Attributes()), ) - tx.EmitContext().SetOriginal(importDecl, node.ExportClause) + tx.EmitContext().SetOriginal(importDecl, node.ExportClause()) var exportDecl *ast.Node if ast.IsExportNamespaceAsDefaultDeclaration(node.AsNode()) { @@ -247,7 +247,7 @@ func (tx *ESModuleTransformer) visitExportDeclaration(node *ast.ExportDeclaratio func (tx *ESModuleTransformer) visitCallExpression(node *ast.CallExpression) *ast.Node { if tx.compilerOptions.RewriteRelativeImportExtensions.IsTrue() { - if ast.IsImportCall(node.AsNode()) && len(node.Arguments.Nodes) > 0 || + if ast.IsImportCall(node.AsNode()) && len(node.Arguments().Nodes) > 0 || ast.IsInJSFile(node.AsNode()) && ast.IsRequireCall(node.AsNode(), false /*requireStringLiteralLikeArgument*/) { return tx.visitImportOrRequireCall(node) } @@ -256,31 +256,31 @@ func (tx *ESModuleTransformer) visitCallExpression(node *ast.CallExpression) *as } func (tx *ESModuleTransformer) visitImportOrRequireCall(node *ast.CallExpression) *ast.Node { - if len(node.Arguments.Nodes) == 0 { + if len(node.Arguments().Nodes) == 0 { return tx.Visitor().VisitEachChild(node.AsNode()) } - expression := tx.Visitor().VisitNode(node.Expression) + expression := tx.Visitor().VisitNode(node.Expression()) var argument *ast.Expression - if ast.IsStringLiteralLike(node.Arguments.Nodes[0]) { - argument = rewriteModuleSpecifier(tx.EmitContext(), node.Arguments.Nodes[0], tx.compilerOptions) + if ast.IsStringLiteralLike(node.Arguments().Nodes[0]) { + argument = rewriteModuleSpecifier(tx.EmitContext(), node.Arguments().Nodes[0], tx.compilerOptions) } else { - argument = tx.Factory().NewRewriteRelativeImportExtensionsHelper(node.Arguments.Nodes[0], tx.compilerOptions.Jsx == core.JsxEmitPreserve) + argument = tx.Factory().NewRewriteRelativeImportExtensionsHelper(node.Arguments().Nodes[0], tx.compilerOptions.Jsx == core.JsxEmitPreserve) } var arguments []*ast.Expression arguments = append(arguments, argument) - rest := core.FirstResult(tx.Visitor().VisitSlice(node.Arguments.Nodes[1:])) + rest := core.FirstResult(tx.Visitor().VisitSlice(node.Arguments().Nodes[1:])) arguments = append(arguments, rest...) argumentList := tx.Factory().NewNodeList(arguments) - argumentList.Loc = node.Arguments.Loc + argumentList.Loc = node.Arguments().Loc return tx.Factory().UpdateCallExpression( node, expression, - node.QuestionDotToken, + node.QuestionDotToken(), nil, /*typeArguments*/ argumentList, node.Flags, diff --git a/tsc/internal/transformers/moduletransforms/externalmoduleinfo.go b/tsc/internal/transformers/moduletransforms/externalmoduleinfo.go index 34354e3adc46f..72bdd16e0470f 100644 --- a/tsc/internal/transformers/moduletransforms/externalmoduleinfo.go +++ b/tsc/internal/transformers/moduletransforms/externalmoduleinfo.go @@ -76,30 +76,30 @@ func (c *externalModuleInfoCollector) collect() *externalModuleInfo { case ast.KindImportEqualsDeclaration: n := node.AsImportEqualsDeclaration() - if ast.IsExternalModuleReference(n.ModuleReference) { + if ast.IsExternalModuleReference(n.ModuleReference()) { // import x = require("mod") c.addExternalImport(node) } case ast.KindExportDeclaration: n := node.AsExportDeclaration() - if n.ModuleSpecifier != nil { + if n.ModuleSpecifier() != nil { // export * from "mod" // export * as ns from "mod" // export { x, y } from "mod" c.addExternalImport(node) - if n.ExportClause == nil { + if n.ExportClause() == nil { // export * from "mod" c.output.hasExportStarsToExportValues = true - } else if ast.IsNamedExports(n.ExportClause) { + } else if ast.IsNamedExports(n.ExportClause()) { // export { x, y } from "mod" c.addExportedNamesForExportDeclaration(n) if !hasImportDefault { - hasImportDefault = containsDefaultReference(n.ExportClause) + hasImportDefault = containsDefaultReference(n.ExportClause()) } } else { // export * as ns from "mod" - name := n.ExportClause.AsNamespaceExport().Name() + name := n.ExportClause().AsNamespaceExport().Name() nameText := name.Text() if c.addUniqueExport(nameText) { c.addExportedBinding(node, name) @@ -123,7 +123,7 @@ func (c *externalModuleInfoCollector) collect() *externalModuleInfo { case ast.KindVariableStatement: n := node.AsVariableStatement() if ast.HasSyntacticModifier(node, ast.ModifierFlagsExport) { - for _, decl := range n.DeclarationList.AsVariableDeclarationList().Declarations.Nodes { + for _, decl := range n.DeclarationList().AsVariableDeclarationList().Declarations().Nodes { c.collectExportedVariableInfo(decl) } } @@ -185,12 +185,12 @@ func (c *externalModuleInfoCollector) addExportedName(name *ast.ModuleExportName } func (c *externalModuleInfoCollector) addExportedNamesForExportDeclaration(node *ast.ExportDeclaration) { - for _, specifier := range node.ExportClause.Elements() { + for _, specifier := range node.ExportClause().Elements() { specifierNameText := specifier.Name().Text() if c.addUniqueExport(specifierNameText) { name := specifier.PropertyNameOrName() if name.Kind != ast.KindStringLiteral { - if node.ModuleSpecifier == nil { + if node.ModuleSpecifier() == nil { c.output.exportSpecifiers.Add(name.Text(), specifier.AsExportSpecifier()) } @@ -361,10 +361,10 @@ func getImportNeedsImportStarHelper(node *ast.ImportDeclaration) bool { if ast.GetNamespaceDeclarationNode(node.AsNode()) != nil { return true } - if node.ImportClause == nil { + if node.ImportClause() == nil { return false } - bindings := node.ImportClause.AsImportClause().NamedBindings + bindings := node.ImportClause().AsImportClause().NamedBindings() if bindings == nil { return false } @@ -373,18 +373,18 @@ func getImportNeedsImportStarHelper(node *ast.ImportDeclaration) bool { } namedImports := bindings.AsNamedImports() defaultRefCount := 0 - for _, binding := range namedImports.Elements.Nodes { + for _, binding := range namedImports.Elements().Nodes { if isNamedDefaultReference(binding) { defaultRefCount++ } } // Import star is required if there's default named refs mixed with non-default refs, or if theres non-default refs and it has a default import - return (defaultRefCount > 0 && defaultRefCount != len(namedImports.Elements.Nodes)) || ((len(namedImports.Elements.Nodes)-defaultRefCount) != 0 && ast.IsDefaultImport(node.AsNode())) + return (defaultRefCount > 0 && defaultRefCount != len(namedImports.Elements().Nodes)) || ((len(namedImports.Elements().Nodes)-defaultRefCount) != 0 && ast.IsDefaultImport(node.AsNode())) } func getImportNeedsImportDefaultHelper(node *ast.ImportDeclaration) bool { // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested) - return !getImportNeedsImportStarHelper(node) && (ast.IsDefaultImport(node.AsNode()) || (node.ImportClause != nil && - ast.IsNamedImports(node.ImportClause.AsImportClause().NamedBindings) && - containsDefaultReference(node.ImportClause.AsImportClause().NamedBindings))) + return !getImportNeedsImportStarHelper(node) && (ast.IsDefaultImport(node.AsNode()) || (node.ImportClause() != nil && + ast.IsNamedImports(node.ImportClause().AsImportClause().NamedBindings()) && + containsDefaultReference(node.ImportClause().AsImportClause().NamedBindings()))) } diff --git a/tsc/internal/transformers/moduletransforms/utilities.go b/tsc/internal/transformers/moduletransforms/utilities.go index fe931df145136..5a6b15ac80651 100644 --- a/tsc/internal/transformers/moduletransforms/utilities.go +++ b/tsc/internal/transformers/moduletransforms/utilities.go @@ -10,10 +10,10 @@ import ( ) func isDeclarationNameOfEnumOrNamespace(emitContext *printer.EmitContext, node *ast.IdentifierNode) bool { - if original := emitContext.MostOriginal(node); original != nil && original.Parent != nil { //nolint:customlint // MostOriginal yields parse-tree nodes and this helper intentionally inspects parse-tree parents. - switch original.Parent.Kind { //nolint:customlint // MostOriginal yields parse-tree nodes and this helper intentionally inspects parse-tree parents. + if original := emitContext.MostOriginal(node); original != nil && original.Parent() != nil { //nolint:customlint // MostOriginal yields parse-tree nodes and this helper intentionally inspects parse-tree parents. + switch original.Parent().Kind { //nolint:customlint // MostOriginal yields parse-tree nodes and this helper intentionally inspects parse-tree parents. case ast.KindEnumDeclaration, ast.KindModuleDeclaration: - return original == original.Parent.Name() //nolint:customlint // MostOriginal yields parse-tree nodes and this helper intentionally inspects parse-tree parents. + return original == original.Parent().Name() //nolint:customlint // MostOriginal yields parse-tree nodes and this helper intentionally inspects parse-tree parents. } } return false diff --git a/tsc/internal/transformers/tstransforms/importelision.go b/tsc/internal/transformers/tstransforms/importelision.go index 35a60f8dc5e65..5d60e3404ef00 100644 --- a/tsc/internal/transformers/tstransforms/importelision.go +++ b/tsc/internal/transformers/tstransforms/importelision.go @@ -45,18 +45,18 @@ func (tx *ImportElisionTransformer) visit(node *ast.Node) *ast.Node { n := node.AsImportDeclaration() // Do not elide a side-effect only import declaration. // import "foo"; - if n.ImportClause != nil { - importClause := tx.Visitor().VisitNode(n.ImportClause) + if n.ImportClause() != nil { + importClause := tx.Visitor().VisitNode(n.ImportClause()) if importClause == nil { return nil } - return tx.Factory().UpdateImportDeclaration(n, n.Modifiers(), importClause, n.ModuleSpecifier, tx.Visitor().VisitNode(n.Attributes)) + return tx.Factory().UpdateImportDeclaration(n, n.Modifiers(), importClause, n.ModuleSpecifier(), tx.Visitor().VisitNode(n.Attributes())) } return tx.Visitor().VisitEachChild(node) case ast.KindImportClause: n := node.AsImportClause() name := core.IfElse(tx.shouldEmitAliasDeclaration(node), n.Name(), nil) - namedBindings := tx.Visitor().VisitNode(n.NamedBindings) + namedBindings := tx.Visitor().VisitNode(n.NamedBindings()) if name == nil && namedBindings == nil { // all import bindings were elided return nil @@ -70,7 +70,7 @@ func (tx *ImportElisionTransformer) visit(node *ast.Node) *ast.Node { return node case ast.KindNamedImports: n := node.AsNamedImports() - elements := tx.Visitor().VisitNodes(n.Elements) + elements := tx.Visitor().VisitNodes(n.Elements()) if len(elements.Nodes) == 0 { // all import specifiers were elided return nil @@ -91,17 +91,17 @@ func (tx *ImportElisionTransformer) visit(node *ast.Node) *ast.Node { case ast.KindExportDeclaration: n := node.AsExportDeclaration() var exportClause *ast.Node - if n.ExportClause != nil { - exportClause = tx.Visitor().VisitNode(n.ExportClause) + if n.ExportClause() != nil { + exportClause = tx.Visitor().VisitNode(n.ExportClause()) if exportClause == nil { // all export bindings were elided return nil } } - return tx.Factory().UpdateExportDeclaration(n, nil /*modifiers*/, false /*isTypeOnly*/, exportClause, tx.Visitor().VisitNode(n.ModuleSpecifier), tx.Visitor().VisitNode(n.Attributes)) + return tx.Factory().UpdateExportDeclaration(n, nil /*modifiers*/, false /*isTypeOnly*/, exportClause, tx.Visitor().VisitNode(n.ModuleSpecifier()), tx.Visitor().VisitNode(n.Attributes())) case ast.KindNamedExports: n := node.AsNamedExports() - elements := tx.Visitor().VisitNodes(n.Elements) + elements := tx.Visitor().VisitNodes(n.Elements()) if len(elements.Nodes) == 0 { // all export specifiers were elided return nil diff --git a/tsc/internal/transformers/tstransforms/legacydecorators.go b/tsc/internal/transformers/tstransforms/legacydecorators.go index 8eaa45e5071ad..26c88a909dbe9 100644 --- a/tsc/internal/transformers/tstransforms/legacydecorators.go +++ b/tsc/internal/transformers/tstransforms/legacydecorators.go @@ -84,9 +84,9 @@ func (tx *LegacyDecoratorsTransformer) visitPropertyAccessExpression(node *ast.P // Visit the expression but not the name, since property access names should not be substituted. // Strada's onSubstituteNode only fires for EmitHint.Expression, which excludes the // .name of PropertyAccessExpression. - expression := tx.Visitor().VisitNode(node.Expression) - if expression != node.Expression { - return tx.Factory().UpdatePropertyAccessExpression(node, expression, node.QuestionDotToken, node.Name(), node.Flags) + expression := tx.Visitor().VisitNode(node.Expression()) + if expression != node.Expression() { + return tx.Factory().UpdatePropertyAccessExpression(node, expression, node.QuestionDotToken(), node.Name(), node.Flags) } return node.AsNode() } @@ -129,11 +129,11 @@ func (tx *LegacyDecoratorsTransformer) visitParamerDeclaration(node *ast.Paramet updated := tx.Factory().UpdateParameterDeclaration( node, elideModifiers(tx.Factory(), node.Modifiers()), - node.DotDotDotToken, + node.DotDotDotToken(), tx.Visitor().VisitNode(node.Name()), nil, nil, - tx.Visitor().VisitNode(node.Initializer), + tx.Visitor().VisitNode(node.Initializer()), ) if updated != node.AsNode() { // While we emit the source map for the node after skipping decorators and modifiers, @@ -153,7 +153,7 @@ func (tx *LegacyDecoratorsTransformer) visitParamerDeclaration(node *ast.Paramet func (tx *LegacyDecoratorsTransformer) visitPropertyNameOfClassElement(member *ast.Node) *ast.Node { name := member.Name() if ast.IsComputedPropertyName(name) && ast.HasDecorators(member) { - expression := tx.Visitor().VisitNode(name.AsComputedPropertyName().Expression) + expression := tx.Visitor().VisitNode(name.AsComputedPropertyName().Expression()) innerExpression := ast.SkipPartiallyEmittedExpressions(expression) if !transformers.IsSimpleInlineableExpression(innerExpression) { generatedName := tx.Factory().NewGeneratedNameForNode(name) @@ -179,7 +179,7 @@ func (tx *LegacyDecoratorsTransformer) visitPropertyDeclaration(node *ast.Proper tx.visitPropertyNameOfClassElement(node.AsNode()), nil, nil, - tx.Visitor().VisitNode(node.Initializer), + tx.Visitor().VisitNode(node.Initializer()), ), node.AsNode(), ) @@ -192,10 +192,10 @@ func (tx *LegacyDecoratorsTransformer) visitGetAccessorDeclaration(node *ast.Get tx.Visitor().VisitModifiers(node.Modifiers()), tx.visitPropertyNameOfClassElement(node.AsNode()), nil, - tx.Visitor().VisitNodes(node.Parameters), + tx.Visitor().VisitNodes(node.Parameters()), nil, nil, - tx.Visitor().VisitNode(node.Body), + tx.Visitor().VisitNode(node.Body()), ), node.AsNode(), ) @@ -208,10 +208,10 @@ func (tx *LegacyDecoratorsTransformer) visitSetAccessorDeclaration(node *ast.Set tx.Visitor().VisitModifiers(node.Modifiers()), tx.visitPropertyNameOfClassElement(node.AsNode()), nil, - tx.Visitor().VisitNodes(node.Parameters), + tx.Visitor().VisitNodes(node.Parameters()), nil, nil, - tx.Visitor().VisitNode(node.Body), + tx.Visitor().VisitNode(node.Body()), ), node.AsNode(), ) @@ -222,14 +222,14 @@ func (tx *LegacyDecoratorsTransformer) visitMethodDeclaration(node *ast.MethodDe tx.Factory().UpdateMethodDeclaration( node, tx.Visitor().VisitModifiers(node.Modifiers()), - node.AsteriskToken, + node.AsteriskToken(), tx.visitPropertyNameOfClassElement(node.AsNode()), nil, nil, - tx.Visitor().VisitNodes(node.Parameters), + tx.Visitor().VisitNodes(node.Parameters()), nil, nil, - tx.Visitor().VisitNode(node.Body), + tx.Visitor().VisitNode(node.Body()), ), node.AsNode(), ) @@ -240,10 +240,10 @@ func (tx *LegacyDecoratorsTransformer) visitConstructorDeclaration(node *ast.Con node, tx.Visitor().VisitModifiers(node.Modifiers()), nil, - tx.Visitor().VisitNodes(node.Parameters), + tx.Visitor().VisitNodes(node.Parameters()), nil, nil, - tx.Visitor().VisitNode(node.Body), + tx.Visitor().VisitNode(node.Body()), ) } @@ -254,8 +254,8 @@ func (tx *LegacyDecoratorsTransformer) visitClassExpression(node *ast.ClassExpre tx.Visitor().VisitModifiers(node.Modifiers()), node.Name(), nil, - tx.Visitor().VisitNodes(node.HeritageClauses), - tx.Visitor().VisitNodes(node.Members), + tx.Visitor().VisitNodes(node.HeritageClauses()), + tx.Visitor().VisitNodes(node.Members()), ) } @@ -282,8 +282,8 @@ func (tx *LegacyDecoratorsTransformer) transformClassDeclarationWithoutClassDeco // ${members} // } modifiers := tx.Visitor().VisitModifiers(node.Modifiers()) - heritageClauses := tx.Visitor().VisitNodes(node.HeritageClauses) - initialMembers := tx.Visitor().VisitNodes(node.Members) + heritageClauses := tx.Visitor().VisitNodes(node.HeritageClauses()) + initialMembers := tx.Visitor().VisitNodes(node.Members()) members, decorationStatements := tx.transformDecoratorsOfClassElements(node, initialMembers) if name == nil && len(decorationStatements) > 0 { @@ -432,8 +432,8 @@ func (tx *LegacyDecoratorsTransformer) transformClassDeclarationWithClassDecorat // ... = class ${name} ${heritageClauses} { // ${members} // } - heritageClauses := tx.Visitor().VisitNodes(node.HeritageClauses) - members := tx.Visitor().VisitNodes(node.Members) + heritageClauses := tx.Visitor().VisitNodes(node.HeritageClauses()) + members := tx.Visitor().VisitNodes(node.Members()) members, decorationStatements := tx.transformDecoratorsOfClassElements(node, members) @@ -523,7 +523,7 @@ func (tx *LegacyDecoratorsTransformer) hasInternalStaticReference(node *ast.Clas } return n.ForEachChild(isOrContainsStaticSelfReference) } - for _, member := range node.Members.Nodes { + for _, member := range node.Members().Nodes { if member.ForEachChild(isOrContainsStaticSelfReference) { return true } @@ -628,10 +628,10 @@ func parameterDecoratorsContainPrivateIdentifierInExpression(parameterDecorators } func hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node *ast.ClassDeclaration) bool { - if node.Members == nil || len(node.Members.Nodes) == 0 { + if node.Members() == nil || len(node.Members().Nodes) == 0 { return false } - for _, member := range node.Members.Nodes { + for _, member := range node.Members().Nodes { if !ast.CanHaveDecorators(member) { continue } @@ -708,7 +708,7 @@ func getAllDecoratorsOfAccessors(accessor *ast.Node, parent *ast.ClassDeclaratio if accessor.Body() == nil { return nil } - decls := ast.GetAllAccessorDeclarations(parent.Members.Nodes, accessor) + decls := ast.GetAllAccessorDeclarations(parent.Members().Nodes, accessor) var firstAccessorWithDecorators *ast.Node if ast.HasDecorators(decls.FirstAccessor) { firstAccessorWithDecorators = decls.FirstAccessor @@ -847,11 +847,11 @@ func isDecoratedClassElement(member *ast.Node, isStaticElement bool, parent *ast * the class. */ func getDecoratedClassElements(node *ast.ClassDeclaration, isStatic bool) []*ast.Node { - if node.Members == nil || len(node.Members.Nodes) == 0 { + if node.Members() == nil || len(node.Members().Nodes) == 0 { return nil } var members []*ast.Node - for _, member := range node.Members.Nodes { + for _, member := range node.Members().Nodes { if isDecoratedClassElement(member, isStatic, node) { members = append(members, member) } @@ -1026,10 +1026,10 @@ func (tx *LegacyDecoratorsTransformer) getExpressionForPropertyName(member *ast. if ast.IsPrivateIdentifier(name) { return tx.Factory().NewIdentifier("") } else if ast.IsComputedPropertyName(name) { - if generateNameForComputedPropertyName && !transformers.IsSimpleInlineableExpression(name.AsComputedPropertyName().Expression) { + if generateNameForComputedPropertyName && !transformers.IsSimpleInlineableExpression(name.AsComputedPropertyName().Expression()) { return tx.Factory().NewGeneratedNameForNode(name) } - return name.AsComputedPropertyName().Expression + return name.AsComputedPropertyName().Expression() } else if ast.IsIdentifier(name) { return tx.Factory().NewStringLiteral(name.Text(), ast.TokenFlagsNone) } else { diff --git a/tsc/internal/transformers/tstransforms/metadata.go b/tsc/internal/transformers/tstransforms/metadata.go index 44f3ed5629a30..a88a9c9036312 100644 --- a/tsc/internal/transformers/tstransforms/metadata.go +++ b/tsc/internal/transformers/tstransforms/metadata.go @@ -99,9 +99,9 @@ func (tx *MetadataTransformer) visitClassExpression(node *ast.ClassExpression) * node, modifiers, tx.Visitor().VisitNode(node.Name()), - tx.Visitor().VisitNodes(node.TypeParameters), - tx.Visitor().VisitNodes(node.HeritageClauses), - tx.Visitor().VisitNodes(node.Members), + tx.Visitor().VisitNodes(node.TypeParameters()), + tx.Visitor().VisitNodes(node.HeritageClauses()), + tx.Visitor().VisitNodes(node.Members()), ) } @@ -118,9 +118,9 @@ func (tx *MetadataTransformer) visitClassDeclaration(node *ast.ClassDeclaration) node, modifiers, tx.Visitor().VisitNode(node.Name()), - tx.Visitor().VisitNodes(node.TypeParameters), - tx.Visitor().VisitNodes(node.HeritageClauses), - tx.Visitor().VisitNodes(node.Members), + tx.Visitor().VisitNodes(node.TypeParameters()), + tx.Visitor().VisitNodes(node.HeritageClauses()), + tx.Visitor().VisitNodes(node.Members()), ) } @@ -134,9 +134,9 @@ func (tx *MetadataTransformer) visitPropertyDeclaration(node *ast.PropertyDeclar node, modifiers, tx.Visitor().VisitNode(node.Name()), - tx.Visitor().VisitNode(node.PostfixToken), - tx.Visitor().VisitNode(node.Type), - tx.Visitor().VisitNode(node.Initializer), + tx.Visitor().VisitNode(node.PostfixToken()), + tx.Visitor().VisitNode(node.Type()), + tx.Visitor().VisitNode(node.Initializer()), ) } @@ -149,14 +149,14 @@ func (tx *MetadataTransformer) visitMethodDeclaration(node *ast.MethodDeclaratio return tx.Factory().UpdateMethodDeclaration( node, modifiers, - tx.Visitor().VisitNode(node.AsteriskToken), + tx.Visitor().VisitNode(node.AsteriskToken()), tx.Visitor().VisitNode(node.Name()), - tx.Visitor().VisitNode(node.PostfixToken), - tx.Visitor().VisitNodes(node.TypeParameters), - tx.Visitor().VisitNodes(node.Parameters), - tx.Visitor().VisitNode(node.Type), - tx.Visitor().VisitNode(node.FullSignature), - tx.Visitor().VisitNode(node.Body), + tx.Visitor().VisitNode(node.PostfixToken()), + tx.Visitor().VisitNodes(node.TypeParameters()), + tx.Visitor().VisitNodes(node.Parameters()), + tx.Visitor().VisitNode(node.Type()), + tx.Visitor().VisitNode(node.FullSignature()), + tx.Visitor().VisitNode(node.Body()), ) } @@ -170,11 +170,11 @@ func (tx *MetadataTransformer) visitSetAccessor(node *ast.SetAccessorDeclaration node, modifiers, tx.Visitor().VisitNode(node.Name()), - tx.Visitor().VisitNodes(node.TypeParameters), - tx.Visitor().VisitNodes(node.Parameters), - tx.Visitor().VisitNode(node.Type), - tx.Visitor().VisitNode(node.FullSignature), - tx.Visitor().VisitNode(node.Body), + tx.Visitor().VisitNodes(node.TypeParameters()), + tx.Visitor().VisitNodes(node.Parameters()), + tx.Visitor().VisitNode(node.Type()), + tx.Visitor().VisitNode(node.FullSignature()), + tx.Visitor().VisitNode(node.Body()), ) } @@ -188,11 +188,11 @@ func (tx *MetadataTransformer) visitGetAccessor(node *ast.GetAccessorDeclaration node, modifiers, tx.Visitor().VisitNode(node.Name()), - tx.Visitor().VisitNodes(node.TypeParameters), - tx.Visitor().VisitNodes(node.Parameters), - tx.Visitor().VisitNode(node.Type), - tx.Visitor().VisitNode(node.FullSignature), - tx.Visitor().VisitNode(node.Body), + tx.Visitor().VisitNodes(node.TypeParameters()), + tx.Visitor().VisitNodes(node.Parameters()), + tx.Visitor().VisitNode(node.Type()), + tx.Visitor().VisitNode(node.FullSignature()), + tx.Visitor().VisitNode(node.Body()), ) } diff --git a/tsc/internal/transformers/tstransforms/runtimesyntax.go b/tsc/internal/transformers/tstransforms/runtimesyntax.go index 35c29262606b0..af01d3211ff48 100644 --- a/tsc/internal/transformers/tstransforms/runtimesyntax.go +++ b/tsc/internal/transformers/tstransforms/runtimesyntax.go @@ -117,10 +117,10 @@ func (tx *RuntimeSyntaxTransformer) visit(node *ast.Node) *ast.Node { node = tx.Visitor().VisitEachChild(node) } case ast.KindImportEqualsDeclaration: - if tx.currentNamespace != nil && tx.currentScope != nil && tx.currentScope.Kind != ast.KindBlock && node.AsImportEqualsDeclaration().ModuleReference.Kind == ast.KindExternalModuleReference { + if tx.currentNamespace != nil && tx.currentScope != nil && tx.currentScope.Kind != ast.KindBlock && node.AsImportEqualsDeclaration().ModuleReference().Kind == ast.KindExternalModuleReference { // do not emit ES6 imports and exports since they are illegal inside a namespace node = nil - } else if tx.currentNamespace != nil && tx.currentScope != nil && tx.currentScope.Kind == ast.KindBlock && node.AsImportEqualsDeclaration().ModuleReference.Kind != ast.KindExternalModuleReference { + } else if tx.currentNamespace != nil && tx.currentScope != nil && tx.currentScope.Kind == ast.KindBlock && node.AsImportEqualsDeclaration().ModuleReference().Kind != ast.KindExternalModuleReference { // inside a block within a namespace, elide internal import aliases node = nil } else { @@ -140,10 +140,10 @@ func (tx *RuntimeSyntaxTransformer) visit(node *ast.Node) *ast.Node { func (tx *RuntimeSyntaxTransformer) recordDeclarationInScope(node *ast.Node) { switch node.Kind { case ast.KindVariableStatement: - tx.recordDeclarationInScope(node.AsVariableStatement().DeclarationList) + tx.recordDeclarationInScope(node.AsVariableStatement().DeclarationList()) return case ast.KindVariableDeclarationList: - for _, decl := range node.AsVariableDeclarationList().Declarations.Nodes { + for _, decl := range node.AsVariableDeclarationList().Declarations().Nodes { tx.recordDeclarationInScope(decl) } return @@ -194,7 +194,7 @@ func (tx *RuntimeSyntaxTransformer) getExpressionForPropertyName(member *ast.Enu case ast.KindComputedPropertyName: n := name.AsComputedPropertyName() // enums don't support computed properties so we always generate the 'expression' part of the name as-is. - return tx.Visitor().VisitNode(n.Expression) + return tx.Visitor().VisitNode(n.Expression()) case ast.KindIdentifier: return tx.Factory().NewStringLiteral(name.Text(), ast.TokenFlagsNone) case ast.KindStringLiteral: // !!! propagate token flags (will produce new diffs) @@ -351,7 +351,7 @@ func (tx *RuntimeSyntaxTransformer) transformEnumBody(node *ast.EnumDeclaration) node = tx.Visitor().VisitEachChild(node.AsNode()).AsEnumDeclaration() statements := []*ast.Statement{} - for i := range len(node.Members.Nodes) { + for i := range len(node.Members().Nodes) { // E[E["A"] = 0] = "A"; statements = tx.transformEnumMember( statements, @@ -361,7 +361,7 @@ func (tx *RuntimeSyntaxTransformer) transformEnumBody(node *ast.EnumDeclaration) } statementList := tx.Factory().NewNodeList(statements) - statementList.Loc = node.Members.Loc + statementList.Loc = node.Members().Loc tx.currentEnum = savedCurrentEnum return tx.Factory().NewBlock(statementList, true /*multiline*/) @@ -373,7 +373,7 @@ func (tx *RuntimeSyntaxTransformer) transformEnumMember( enum *ast.EnumDeclaration, index int, ) []*ast.Statement { - memberNode := enum.Members.Nodes[index] + memberNode := enum.Members().Nodes[index] member := memberNode.AsEnumMember() savedParent := tx.parentNode @@ -382,7 +382,7 @@ func (tx *RuntimeSyntaxTransformer) transformEnumMember( // E[E["A"] = x] = "A"; // ^ - expression := member.Initializer // NOTE: already visited + expression := member.Initializer() // NOTE: already visited var useExplicitReverseMapping bool @@ -497,20 +497,20 @@ func (tx *RuntimeSyntaxTransformer) transformModuleBody(node *ast.ModuleDeclarat var statementsLocation core.TextRange var blockLocation core.TextRange - if node.Body != nil { - if node.Body.Kind == ast.KindModuleBlock { + if node.Body() != nil { + if node.Body().Kind == ast.KindModuleBlock { // visit the children of `node` in advance to capture any references to namespace members node = tx.Visitor().VisitEachChild(node.AsNode()).AsModuleDeclaration() - body := node.Body.AsModuleBlock() - statements = body.Statements.Nodes - statementsLocation = body.Statements.Loc + body := node.Body().AsModuleBlock() + statements = body.Statements().Nodes + statementsLocation = body.Statements().Loc blockLocation = body.Loc } else { // node.Body.Kind == ast.KindModuleDeclaration // !!! Strada didn't do this; why? // tx.currentScope = node.AsNode() - statements, _ = tx.Visitor().VisitSlice([]*ast.Node{node.Body}) - moduleBlock := getInnermostModuleDeclarationFromDottedModule(node).Body.AsModuleBlock() - statementsLocation = moduleBlock.Statements.Loc.WithPos(-1) + statements, _ = tx.Visitor().VisitSlice([]*ast.Node{node.Body()}) + moduleBlock := getInnermostModuleDeclarationFromDottedModule(node).Body().AsModuleBlock() + statementsLocation = moduleBlock.Statements().Loc.WithPos(-1) } } @@ -545,18 +545,18 @@ func (tx *RuntimeSyntaxTransformer) transformModuleBody(node *ast.ModuleDeclarat // })(hello || (hello = {})); // // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if node.Body == nil || node.Body.Kind != ast.KindModuleBlock { + if node.Body() == nil || node.Body().Kind != ast.KindModuleBlock { tx.EmitContext().AddEmitFlags(block, printer.EFNoComments) } return block } func (tx *RuntimeSyntaxTransformer) visitImportEqualsDeclaration(node *ast.ImportEqualsDeclaration) *ast.Node { - if node.ModuleReference.Kind == ast.KindExternalModuleReference { + if node.ModuleReference().Kind == ast.KindExternalModuleReference { return tx.Visitor().VisitEachChild(node.AsNode()) } - moduleReference := tx.Factory().CreateExpressionFromEntityName(node.ModuleReference) + moduleReference := tx.Factory().CreateExpressionFromEntityName(node.ModuleReference()) tx.EmitContext().SetEmitFlags(moduleReference, printer.EFNoComments|printer.EFNoNestedComments) if !tx.isExportOfNamespace(node.AsNode()) { // export var ${name} = ${moduleReference}; @@ -580,9 +580,9 @@ func (tx *RuntimeSyntaxTransformer) visitImportEqualsDeclaration(node *ast.Impor func (tx *RuntimeSyntaxTransformer) visitVariableStatement(node *ast.VariableStatement) *ast.Node { if tx.isExportOfNamespace(node.AsNode()) { expressions := []*ast.Expression{} - for _, declaration := range node.DeclarationList.AsVariableDeclarationList().Declarations.Nodes { + for _, declaration := range node.DeclarationList().AsVariableDeclarationList().Declarations().Nodes { v := declaration.AsVariableDeclaration() - if v.Initializer == nil { + if v.Initializer() == nil { continue } if ast.IsBindingPattern(v.Name()) { @@ -637,13 +637,13 @@ func (tx *RuntimeSyntaxTransformer) visitFunctionDeclaration(node *ast.FunctionD updated := tx.Factory().UpdateFunctionDeclaration( node, tx.Visitor().VisitModifiers(transformers.ExtractModifiers(tx.EmitContext(), node.Modifiers(), ^ast.ModifierFlagsExport)), - node.AsteriskToken, + node.AsteriskToken(), tx.Visitor().VisitNode(node.Name()), nil, /*typeParameters*/ - tx.Visitor().VisitNodes(node.Parameters), + tx.Visitor().VisitNodes(node.Parameters()), nil, /*returnType*/ nil, /*fullSignature*/ - tx.Visitor().VisitNode(node.Body), + tx.Visitor().VisitNode(node.Body()), ) export := tx.createExportStatementForDeclaration(node.AsNode()) if export != nil { @@ -679,9 +679,9 @@ func (tx *RuntimeSyntaxTransformer) visitClassDeclaration(node *ast.ClassDeclara if name == nil && (exported || ast.ChildIsDecorated(tx.compilerOptions.ExperimentalDecorators.IsTrue(), node.AsNode(), nil)) { name = tx.Factory().NewGeneratedNameForNode(node.AsNode()) } - heritageClauses := tx.Visitor().VisitNodes(node.HeritageClauses) - members := tx.Visitor().VisitNodes(node.Members) - parameterProperties := tx.getParameterProperties(core.Find(node.Members.Nodes, ast.IsConstructorDeclaration)) + heritageClauses := tx.Visitor().VisitNodes(node.HeritageClauses()) + members := tx.Visitor().VisitNodes(node.Members()) + parameterProperties := tx.getParameterProperties(core.Find(node.Members().Nodes, ast.IsConstructorDeclaration)) if len(parameterProperties) > 0 { var newMembers []*ast.ClassElement @@ -701,7 +701,7 @@ func (tx *RuntimeSyntaxTransformer) visitClassDeclaration(node *ast.ClassDeclara if len(newMembers) > 0 { newMembers = append(newMembers, members.Nodes...) members = tx.Factory().NewNodeList(newMembers) - members.Loc = node.Members.Loc + members.Loc = node.Members().Loc } } @@ -718,9 +718,9 @@ func (tx *RuntimeSyntaxTransformer) visitClassDeclaration(node *ast.ClassDeclara func (tx *RuntimeSyntaxTransformer) visitClassExpression(node *ast.ClassExpression) *ast.Node { modifiers := tx.Visitor().VisitModifiers(transformers.ExtractModifiers(tx.EmitContext(), node.Modifiers(), ^ast.ModifierFlagsExportDefault)) name := tx.Visitor().VisitNode(node.Name()) - heritageClauses := tx.Visitor().VisitNodes(node.HeritageClauses) - members := tx.Visitor().VisitNodes(node.Members) - parameterProperties := tx.getParameterProperties(core.Find(node.Members.Nodes, ast.IsConstructorDeclaration)) + heritageClauses := tx.Visitor().VisitNodes(node.HeritageClauses()) + members := tx.Visitor().VisitNodes(node.Members()) + parameterProperties := tx.getParameterProperties(core.Find(node.Members().Nodes, ast.IsConstructorDeclaration)) if len(parameterProperties) > 0 { var newMembers []*ast.ClassElement @@ -740,7 +740,7 @@ func (tx *RuntimeSyntaxTransformer) visitClassExpression(node *ast.ClassExpressi if len(newMembers) > 0 { newMembers = append(newMembers, members.Nodes...) members = tx.Factory().NewNodeList(newMembers) - members.Loc = node.Members.Loc + members.Loc = node.Members().Loc } } @@ -750,7 +750,7 @@ func (tx *RuntimeSyntaxTransformer) visitClassExpression(node *ast.ClassExpressi func (tx *RuntimeSyntaxTransformer) visitConstructorDeclaration(node *ast.ConstructorDeclaration) *ast.Node { modifiers := tx.Visitor().VisitModifiers(node.Modifiers()) parameters := tx.EmitContext().VisitParameters(node.ParameterList(), tx.Visitor()) - body := tx.visitConstructorBody(node.Body.AsBlock(), node.AsNode()) + body := tx.visitConstructorBody(node.Body().AsBlock(), node.AsNode()) return tx.Factory().UpdateConstructorDeclaration(node, modifiers, nil /*typeParameters*/, parameters, nil /*returnType*/, nil /*fullSignature*/, body) } @@ -764,7 +764,7 @@ func (tx *RuntimeSyntaxTransformer) visitConstructorBody(body *ast.Block, constr savedCurrentScope, savedCurrentScopeFirstDeclarationsOfName := tx.pushScope(body.AsNode()) tx.EmitContext().StartVariableEnvironment() - prologue, rest := tx.Factory().SplitStandardPrologue(body.Statements.Nodes) + prologue, rest := tx.Factory().SplitStandardPrologue(body.Statements().Nodes) statements := slices.Clone(prologue) // Transform parameters into property assignments. Transforms this: @@ -784,11 +784,11 @@ func (tx *RuntimeSyntaxTransformer) visitConstructorBody(body *ast.Block, constr for _, parameter := range parameterProperties { if ast.IsIdentifier(parameter.Name()) { propertyName := parameter.Name().Clone(tx.Factory()) - propertyName.Parent = parameter.Name().Parent //nolint:customlint // .Parent set to get node to printback using text from original file instead of processed text; TODO: this should be achievable via EmitFlags instead + propertyName.SetParent(parameter.Name().Parent()) //nolint:customlint // .Parent set to get node to printback using text from original file instead of processed text; TODO: this should be achievable via EmitFlags instead tx.EmitContext().AddEmitFlags(propertyName, printer.EFNoComments|printer.EFNoSourceMap) localName := parameter.Name().Clone(tx.Factory()) - localName.Parent = parameter.Name().Parent //nolint:customlint // .Parent set to get node to printback using text from original file instead of processed text; TODO: this should be achievable via EmitFlags instead + localName.SetParent(parameter.Name().Parent()) //nolint:customlint // .Parent set to get node to printback using text from original file instead of processed text; TODO: this should be achievable via EmitFlags instead tx.EmitContext().AddEmitFlags(localName, printer.EFNoComments) parameterProperty := tx.Factory().NewExpressionStatement( @@ -819,7 +819,7 @@ func (tx *RuntimeSyntaxTransformer) visitConstructorBody(body *ast.Block, constr statements = tx.EmitContext().EndAndMergeVariableEnvironment(statements) statementList := tx.Factory().NewNodeList(statements) - statementList.Loc = body.Statements.Loc + statementList.Loc = body.Statements().Loc tx.popScope(savedCurrentScope, savedCurrentScopeFirstDeclarationsOfName) tx.popNode(grandparentOfBody) @@ -840,7 +840,7 @@ func (tx *RuntimeSyntaxTransformer) transformConstructorBodyWorker(statementsIn // if the statement containing `super` is a `try` statement, transform the body of the `try` block if ast.IsTryStatement(superStatement) { tryStatement := superStatement.AsTryStatement() - tryBlock := tryStatement.TryBlock.AsBlock() + tryBlock := tryStatement.TryBlock().AsBlock() // keep track of hierarchy as we descend grandparentOfTryStatement := tx.pushNode(tryStatement.AsNode()) @@ -849,7 +849,7 @@ func (tx *RuntimeSyntaxTransformer) transformConstructorBodyWorker(statementsIn // visit the `try` block tryBlockStatements := tx.transformConstructorBodyWorker( - tryBlock.Statements.Nodes, + tryBlock.Statements().Nodes, superPath[1:], initializerStatements, ) @@ -859,12 +859,12 @@ func (tx *RuntimeSyntaxTransformer) transformConstructorBodyWorker(statementsIn tx.popNode(grandparentOfTryBlock) tryBlockStatementList := tx.Factory().NewNodeList(tryBlockStatements) - tryBlockStatementList.Loc = tryBlock.Statements.Loc + tryBlockStatementList.Loc = tryBlock.Statements().Loc statementsOut = append(statementsOut, tx.Factory().UpdateTryStatement( tryStatement, tx.Factory().UpdateBlock(tryBlock, tryBlockStatementList, tryBlock.MultiLine), - tx.Visitor().VisitNode(tryStatement.CatchClause), - tx.Visitor().VisitNode(tryStatement.FinallyBlock), + tx.Visitor().VisitNode(tryStatement.CatchClause()), + tx.Visitor().VisitNode(tryStatement.FinallyBlock()), )) // restore hierarchy as we ascend to the parent of the `try` statement @@ -887,8 +887,8 @@ func (tx *RuntimeSyntaxTransformer) visitShorthandPropertyAssignment(node *ast.S exportedOrImportedName := tx.visitExpressionIdentifier(name) if exportedOrImportedName != name { expression := exportedOrImportedName - if node.ObjectAssignmentInitializer != nil { - equalsToken := node.EqualsToken + if node.ObjectAssignmentInitializer() != nil { + equalsToken := node.EqualsToken() if equalsToken == nil { equalsToken = tx.Factory().NewToken(ast.KindEqualsToken) } @@ -897,7 +897,7 @@ func (tx *RuntimeSyntaxTransformer) visitShorthandPropertyAssignment(node *ast.S expression, nil, /*typeNode*/ equalsToken, - tx.Visitor().VisitNode(node.ObjectAssignmentInitializer), + tx.Visitor().VisitNode(node.ObjectAssignmentInitializer()), ) } @@ -913,8 +913,8 @@ func (tx *RuntimeSyntaxTransformer) visitShorthandPropertyAssignment(node *ast.S exportedOrImportedName, nil, /*postfixToken*/ nil, /*typeNode*/ - node.EqualsToken, - tx.Visitor().VisitNode(node.ObjectAssignmentInitializer), + node.EqualsToken(), + tx.Visitor().VisitNode(node.ObjectAssignmentInitializer()), ) } @@ -988,8 +988,8 @@ func (tx *RuntimeSyntaxTransformer) shouldEmitModuleDeclaration(node *ast.Module } func getInnermostModuleDeclarationFromDottedModule(moduleDeclaration *ast.ModuleDeclaration) *ast.ModuleDeclaration { - for moduleDeclaration.Body != nil && moduleDeclaration.Body.Kind == ast.KindModuleDeclaration { - moduleDeclaration = moduleDeclaration.Body.AsModuleDeclaration() + for moduleDeclaration.Body() != nil && moduleDeclaration.Body().Kind == ast.KindModuleDeclaration { + moduleDeclaration = moduleDeclaration.Body().AsModuleDeclaration() } return moduleDeclaration } diff --git a/tsc/internal/transformers/tstransforms/typeeraser.go b/tsc/internal/transformers/tstransforms/typeeraser.go index 0cf768b9d894a..8f15bfe6264cf 100644 --- a/tsc/internal/transformers/tstransforms/typeeraser.go +++ b/tsc/internal/transformers/tstransforms/typeeraser.go @@ -122,7 +122,7 @@ func (tx *TypeEraserTransformer) visit(node *ast.Node) *ast.Node { case ast.KindModuleDeclaration: if !ast.IsIdentifier(node.Name()) || !ast.IsInstantiatedModule(node, tx.compilerOptions.ShouldPreserveConstEnums()) || - getInnermostModuleDeclarationFromDottedModule(node.AsModuleDeclaration()).Body == nil { + getInnermostModuleDeclarationFromDottedModule(node.AsModuleDeclaration()).Body() == nil { // TypeScript module declarations are elided if they are not instantiated or have no body return tx.elide(node) } @@ -130,66 +130,66 @@ func (tx *TypeEraserTransformer) visit(node *ast.Node) *ast.Node { case ast.KindExpressionWithTypeArguments: n := node.AsExpressionWithTypeArguments() - return tx.Factory().UpdateExpressionWithTypeArguments(n, tx.Visitor().VisitNode(n.Expression), nil) + return tx.Factory().UpdateExpressionWithTypeArguments(n, tx.Visitor().VisitNode(n.Expression()), nil) case ast.KindPropertyDeclaration: if tx.compilerOptions.ExperimentalDecorators.IsTrue() && ast.HasSyntacticModifier(node, ast.ModifierFlagsAmbient|ast.ModifierFlagsAbstract) && ast.HasDecorators(node) { // declare/abstract props with decorators must be preserved until the decorator transform can process them and remove them n := node.AsPropertyDeclaration() - return tx.Factory().UpdatePropertyDeclaration(n, tx.Visitor().VisitModifiers(n.Modifiers()), tx.Visitor().VisitNode(n.Name()), nil, nil, tx.Visitor().VisitNode(n.Initializer)) + return tx.Factory().UpdatePropertyDeclaration(n, tx.Visitor().VisitModifiers(n.Modifiers()), tx.Visitor().VisitNode(n.Name()), nil, nil, tx.Visitor().VisitNode(n.Initializer())) } if ast.HasSyntacticModifier(node, ast.ModifierFlagsAmbient|ast.ModifierFlagsAbstract) { // TypeScript `declare` fields are elided return nil } n := node.AsPropertyDeclaration() - return tx.Factory().UpdatePropertyDeclaration(n, tx.Visitor().VisitModifiers(n.Modifiers()), tx.Visitor().VisitNode(n.Name()), nil, nil, tx.Visitor().VisitNode(n.Initializer)) + return tx.Factory().UpdatePropertyDeclaration(n, tx.Visitor().VisitModifiers(n.Modifiers()), tx.Visitor().VisitNode(n.Name()), nil, nil, tx.Visitor().VisitNode(n.Initializer())) case ast.KindConstructor: n := node.AsConstructorDeclaration() - if ast.NodeIsMissing(n.Body) { + if ast.NodeIsMissing(n.Body()) { // TypeScript overloads are elided return nil } - return tx.Factory().UpdateConstructorDeclaration(n, nil, nil, tx.Visitor().VisitNodes(n.Parameters), nil, nil, tx.Visitor().VisitNode(n.Body)) + return tx.Factory().UpdateConstructorDeclaration(n, nil, nil, tx.Visitor().VisitNodes(n.Parameters()), nil, nil, tx.Visitor().VisitNode(n.Body())) case ast.KindMethodDeclaration: n := node.AsMethodDeclaration() - if ast.NodeIsMissing(n.Body) { + if ast.NodeIsMissing(n.Body()) { // TypeScript overloads are elided return nil } - return tx.Factory().UpdateMethodDeclaration(n, tx.Visitor().VisitModifiers(n.Modifiers()), n.AsteriskToken, tx.Visitor().VisitNode(n.Name()), nil, nil, tx.Visitor().VisitNodes(n.Parameters), nil, nil, tx.Visitor().VisitNode(n.Body)) + return tx.Factory().UpdateMethodDeclaration(n, tx.Visitor().VisitModifiers(n.Modifiers()), n.AsteriskToken(), tx.Visitor().VisitNode(n.Name()), nil, nil, tx.Visitor().VisitNodes(n.Parameters()), nil, nil, tx.Visitor().VisitNode(n.Body())) case ast.KindGetAccessor: n := node.AsGetAccessorDeclaration() - if ast.NodeIsMissing(n.Body) && ast.HasSyntacticModifier(node, ast.ModifierFlagsAbstract) { + if ast.NodeIsMissing(n.Body()) && ast.HasSyntacticModifier(node, ast.ModifierFlagsAbstract) { // Abstract accessors are elided return nil } - body := tx.Visitor().VisitNode(n.Body) + body := tx.Visitor().VisitNode(n.Body()) if body == nil { body = tx.Factory().NewBlock(tx.Factory().NewNodeList(nil), false) } - return tx.Factory().UpdateGetAccessorDeclaration(n, tx.Visitor().VisitModifiers(n.Modifiers()), tx.Visitor().VisitNode(n.Name()), nil, tx.Visitor().VisitNodes(n.Parameters), nil, nil, body) + return tx.Factory().UpdateGetAccessorDeclaration(n, tx.Visitor().VisitModifiers(n.Modifiers()), tx.Visitor().VisitNode(n.Name()), nil, tx.Visitor().VisitNodes(n.Parameters()), nil, nil, body) case ast.KindSetAccessor: n := node.AsSetAccessorDeclaration() - if ast.NodeIsMissing(n.Body) && ast.HasSyntacticModifier(node, ast.ModifierFlagsAbstract) { + if ast.NodeIsMissing(n.Body()) && ast.HasSyntacticModifier(node, ast.ModifierFlagsAbstract) { // Abstract accessors are elided return nil } - body := tx.Visitor().VisitNode(n.Body) + body := tx.Visitor().VisitNode(n.Body()) if body == nil { body = tx.Factory().NewBlock(tx.Factory().NewNodeList(nil), false) } - return tx.Factory().UpdateSetAccessorDeclaration(n, tx.Visitor().VisitModifiers(n.Modifiers()), tx.Visitor().VisitNode(n.Name()), nil, tx.Visitor().VisitNodes(n.Parameters), nil, nil, body) + return tx.Factory().UpdateSetAccessorDeclaration(n, tx.Visitor().VisitModifiers(n.Modifiers()), tx.Visitor().VisitNode(n.Name()), nil, tx.Visitor().VisitNodes(n.Parameters()), nil, nil, body) case ast.KindVariableDeclaration: n := node.AsVariableDeclaration() - updated := tx.Factory().UpdateVariableDeclaration(n, tx.Visitor().VisitNode(n.Name()), nil, nil, tx.Visitor().VisitNode(n.Initializer)) - if n.Type != nil { - tx.EmitContext().SetTypeNode(updated.AsVariableDeclaration().Name(), n.Type) + updated := tx.Factory().UpdateVariableDeclaration(n, tx.Visitor().VisitNode(n.Name()), nil, nil, tx.Visitor().VisitNode(n.Initializer())) + if n.Type() != nil { + tx.EmitContext().SetTypeNode(updated.AsVariableDeclaration().Name(), n.Type()) } return updated @@ -199,31 +199,31 @@ func (tx *TypeEraserTransformer) visit(node *ast.Node) *ast.Node { // TypeScript `implements` clauses are elided return nil } - return tx.Factory().UpdateHeritageClause(n, n.Token, tx.Visitor().VisitNodes(n.Types)) + return tx.Factory().UpdateHeritageClause(n, n.Token, tx.Visitor().VisitNodes(n.Types())) case ast.KindClassDeclaration: n := node.AsClassDeclaration() - return tx.Factory().UpdateClassDeclaration(n, tx.Visitor().VisitModifiers(n.Modifiers()), tx.Visitor().VisitNode(n.Name()), nil, tx.Visitor().VisitNodes(n.HeritageClauses), tx.Visitor().VisitNodes(n.Members)) + return tx.Factory().UpdateClassDeclaration(n, tx.Visitor().VisitModifiers(n.Modifiers()), tx.Visitor().VisitNode(n.Name()), nil, tx.Visitor().VisitNodes(n.HeritageClauses()), tx.Visitor().VisitNodes(n.Members())) case ast.KindClassExpression: n := node.AsClassExpression() - return tx.Factory().UpdateClassExpression(n, tx.Visitor().VisitModifiers(n.Modifiers()), tx.Visitor().VisitNode(n.Name()), nil, tx.Visitor().VisitNodes(n.HeritageClauses), tx.Visitor().VisitNodes(n.Members)) + return tx.Factory().UpdateClassExpression(n, tx.Visitor().VisitModifiers(n.Modifiers()), tx.Visitor().VisitNode(n.Name()), nil, tx.Visitor().VisitNodes(n.HeritageClauses()), tx.Visitor().VisitNodes(n.Members())) case ast.KindFunctionDeclaration: n := node.AsFunctionDeclaration() - if ast.NodeIsMissing(n.Body) { + if ast.NodeIsMissing(n.Body()) { // TypeScript overloads are elided return tx.elide(node) } - return tx.Factory().UpdateFunctionDeclaration(n, tx.Visitor().VisitModifiers(n.Modifiers()), n.AsteriskToken, tx.Visitor().VisitNode(n.Name()), nil, tx.Visitor().VisitNodes(n.Parameters), nil, nil, tx.Visitor().VisitNode(n.Body)) + return tx.Factory().UpdateFunctionDeclaration(n, tx.Visitor().VisitModifiers(n.Modifiers()), n.AsteriskToken(), tx.Visitor().VisitNode(n.Name()), nil, tx.Visitor().VisitNodes(n.Parameters()), nil, nil, tx.Visitor().VisitNode(n.Body())) case ast.KindFunctionExpression: n := node.AsFunctionExpression() - return tx.Factory().UpdateFunctionExpression(n, tx.Visitor().VisitModifiers(n.Modifiers()), n.AsteriskToken, tx.Visitor().VisitNode(n.Name()), nil, tx.Visitor().VisitNodes(n.Parameters), nil, nil, tx.Visitor().VisitNode(n.Body)) + return tx.Factory().UpdateFunctionExpression(n, tx.Visitor().VisitModifiers(n.Modifiers()), n.AsteriskToken(), tx.Visitor().VisitNode(n.Name()), nil, tx.Visitor().VisitNodes(n.Parameters()), nil, nil, tx.Visitor().VisitNode(n.Body())) case ast.KindArrowFunction: n := node.AsArrowFunction() - return tx.Factory().UpdateArrowFunction(n, tx.Visitor().VisitModifiers(n.Modifiers()), nil, tx.Visitor().VisitNodes(n.Parameters), nil, nil, n.EqualsGreaterThanToken, tx.Visitor().VisitNode(n.Body)) + return tx.Factory().UpdateArrowFunction(n, tx.Visitor().VisitModifiers(n.Modifiers()), nil, tx.Visitor().VisitNodes(n.Parameters()), nil, nil, n.EqualsGreaterThanToken(), tx.Visitor().VisitNode(n.Body())) case ast.KindParameter: if ast.IsThisParameter(node) { @@ -246,19 +246,19 @@ func (tx *TypeEraserTransformer) visit(node *ast.Node) *ast.Node { modifiers = tx.Factory().NewModifierList(slices.Concat(modifiers.Nodes, visited)) } } - return tx.Factory().UpdateParameterDeclaration(n, modifiers, n.DotDotDotToken, tx.Visitor().VisitNode(n.Name()), nil, nil, tx.Visitor().VisitNode(n.Initializer)) + return tx.Factory().UpdateParameterDeclaration(n, modifiers, n.DotDotDotToken(), tx.Visitor().VisitNode(n.Name()), nil, nil, tx.Visitor().VisitNode(n.Initializer())) case ast.KindCallExpression: n := node.AsCallExpression() - return tx.Factory().UpdateCallExpression(n, tx.Visitor().VisitNode(n.Expression), n.QuestionDotToken, nil, tx.Visitor().VisitNodes(n.Arguments), n.Flags) + return tx.Factory().UpdateCallExpression(n, tx.Visitor().VisitNode(n.Expression()), n.QuestionDotToken(), nil, tx.Visitor().VisitNodes(n.Arguments()), n.Flags) case ast.KindNewExpression: n := node.AsNewExpression() - return tx.Factory().UpdateNewExpression(n, tx.Visitor().VisitNode(n.Expression), nil, tx.Visitor().VisitNodes(n.Arguments)) + return tx.Factory().UpdateNewExpression(n, tx.Visitor().VisitNode(n.Expression()), nil, tx.Visitor().VisitNodes(n.Arguments())) case ast.KindTaggedTemplateExpression: n := node.AsTaggedTemplateExpression() - return tx.Factory().UpdateTaggedTemplateExpression(n, tx.Visitor().VisitNode(n.Tag), n.QuestionDotToken, nil, tx.Visitor().VisitNode(n.Template), n.Flags) + return tx.Factory().UpdateTaggedTemplateExpression(n, tx.Visitor().VisitNode(n.Tag()), n.QuestionDotToken(), nil, tx.Visitor().VisitNode(n.Template()), n.Flags) case ast.KindNonNullExpression, ast.KindTypeAssertionExpression, ast.KindAsExpression, ast.KindSatisfiesExpression: partial := tx.Factory().NewPartiallyEmittedExpression(tx.Visitor().VisitNode(node.Expression())) @@ -269,9 +269,9 @@ func (tx *TypeEraserTransformer) visit(node *ast.Node) *ast.Node { case ast.KindParenthesizedExpression: if !ast.IsJSDocTypeAssertion(node) { n := node.AsParenthesizedExpression() - expression := ast.SkipOuterExpressions(n.Expression, ast.OEKAllExceptAssertionsOrExpressionsWithTypeArguments) + expression := ast.SkipOuterExpressions(n.Expression(), ast.OEKAllExceptAssertionsOrExpressionsWithTypeArguments) if ast.IsAssertionExpression(expression) || ast.IsSatisfiesExpression(expression) { - partial := tx.Factory().NewPartiallyEmittedExpression(tx.Visitor().VisitNode(n.Expression)) + partial := tx.Factory().NewPartiallyEmittedExpression(tx.Visitor().VisitNode(n.Expression())) tx.EmitContext().SetOriginal(partial, node) partial.Loc = node.Loc return partial @@ -281,11 +281,11 @@ func (tx *TypeEraserTransformer) visit(node *ast.Node) *ast.Node { case ast.KindJsxSelfClosingElement: n := node.AsJsxSelfClosingElement() - return tx.Factory().UpdateJsxSelfClosingElement(n, tx.Visitor().VisitNode(n.TagName), nil, tx.Visitor().VisitNode(n.Attributes)) + return tx.Factory().UpdateJsxSelfClosingElement(n, tx.Visitor().VisitNode(n.TagName()), nil, tx.Visitor().VisitNode(n.Attributes())) case ast.KindJsxOpeningElement: n := node.AsJsxOpeningElement() - return tx.Factory().UpdateJsxOpeningElement(n, tx.Visitor().VisitNode(n.TagName), nil, tx.Visitor().VisitNode(n.Attributes)) + return tx.Factory().UpdateJsxOpeningElement(n, tx.Visitor().VisitNode(n.TagName()), nil, tx.Visitor().VisitNode(n.Attributes())) case ast.KindImportEqualsDeclaration: n := node.AsImportEqualsDeclaration() @@ -297,16 +297,16 @@ func (tx *TypeEraserTransformer) visit(node *ast.Node) *ast.Node { case ast.KindImportDeclaration: n := node.AsImportDeclaration() - if n.ImportClause == nil { + if n.ImportClause() == nil { // Do not elide a side-effect only import declaration. // import "foo"; return node } - importClause := tx.Visitor().VisitNode(n.ImportClause) + importClause := tx.Visitor().VisitNode(n.ImportClause()) if importClause == nil { return nil } - return tx.Factory().UpdateImportDeclaration(n, n.Modifiers(), importClause, n.ModuleSpecifier, n.Attributes) + return tx.Factory().UpdateImportDeclaration(n, n.Modifiers(), importClause, n.ModuleSpecifier(), n.Attributes()) case ast.KindImportClause: n := node.AsImportClause() @@ -315,11 +315,11 @@ func (tx *TypeEraserTransformer) visit(node *ast.Node) *ast.Node { return nil } name := n.Name() - namedBindings := tx.Visitor().VisitNode(n.NamedBindings) + namedBindings := tx.Visitor().VisitNode(n.NamedBindings()) // Empty {} due to type-only import erasure can be skipped if there is also a default import if name != nil && namedBindings != nil && ast.IsNamedImports(namedBindings) && - len(namedBindings.AsNamedImports().Elements.Nodes) == 0 && - len(n.NamedBindings.AsNamedImports().Elements.Nodes) != 0 { + len(namedBindings.AsNamedImports().Elements().Nodes) == 0 && + len(n.NamedBindings().AsNamedImports().Elements().Nodes) != 0 { // the default binding keeps the import; a source-written {} is left as is namedBindings = nil } @@ -331,11 +331,11 @@ func (tx *TypeEraserTransformer) visit(node *ast.Node) *ast.Node { case ast.KindNamedImports: n := node.AsNamedImports() - if len(n.Elements.Nodes) == 0 { + if len(n.Elements().Nodes) == 0 { // Do not elide a side-effect only import declaration. return node } - elements := tx.Visitor().VisitNodes(n.Elements) + elements := tx.Visitor().VisitNodes(n.Elements()) if !tx.compilerOptions.VerbatimModuleSyntax.IsTrue() && len(elements.Nodes) == 0 { // all import specifiers were elided return nil @@ -357,23 +357,23 @@ func (tx *TypeEraserTransformer) visit(node *ast.Node) *ast.Node { return nil } var exportClause *ast.Node - if n.ExportClause != nil { - exportClause = tx.Visitor().VisitNode(n.ExportClause) + if n.ExportClause() != nil { + exportClause = tx.Visitor().VisitNode(n.ExportClause()) if exportClause == nil { // all export bindings were elided return nil } } - return tx.Factory().UpdateExportDeclaration(n, nil /*modifiers*/, false /*isTypeOnly*/, exportClause, tx.Visitor().VisitNode(n.ModuleSpecifier), tx.Visitor().VisitNode(n.Attributes)) + return tx.Factory().UpdateExportDeclaration(n, nil /*modifiers*/, false /*isTypeOnly*/, exportClause, tx.Visitor().VisitNode(n.ModuleSpecifier()), tx.Visitor().VisitNode(n.Attributes())) case ast.KindNamedExports: n := node.AsNamedExports() - if len(n.Elements.Nodes) == 0 { + if len(n.Elements().Nodes) == 0 { // Do not elide an empty export declaration. return node } - elements := tx.Visitor().VisitNodes(n.Elements) + elements := tx.Visitor().VisitNodes(n.Elements()) if !tx.compilerOptions.VerbatimModuleSyntax.IsTrue() && len(elements.Nodes) == 0 { // all export specifiers were elided return nil diff --git a/tsc/internal/transformers/tstransforms/typeserializer.go b/tsc/internal/transformers/tstransforms/typeserializer.go index 21c5d183370a5..7a89b4607b1f6 100644 --- a/tsc/internal/transformers/tstransforms/typeserializer.go +++ b/tsc/internal/transformers/tstransforms/typeserializer.go @@ -53,11 +53,11 @@ func (s *metadataSerializer) SerializeReturnTypeOfNode(ctx metadataSerializerCon } func GetSetAccessorValueParameter(node *ast.SetAccessorDeclaration) *ast.Node { - if node != nil && len(node.Parameters.Nodes) > 0 { - if len(node.Parameters.Nodes) >= 2 && ast.IsThisParameter(node.Parameters.Nodes[0]) { - return node.Parameters.Nodes[1] + if node != nil && len(node.Parameters().Nodes) > 0 { + if len(node.Parameters().Nodes) >= 2 && ast.IsThisParameter(node.Parameters().Nodes[0]) { + return node.Parameters().Nodes[1] } - return node.Parameters.Nodes[0] + return node.Parameters().Nodes[0] } return nil } @@ -81,7 +81,7 @@ func getAccessorTypeNode(node *ast.Node, container *ast.Node) *ast.Node { return getSetAccessorTypeAnnotationNode(accessors.SetAccessor) } if accessors.GetAccessor != nil { - return accessors.GetAccessor.Type + return accessors.GetAccessor.Type() } return nil } @@ -125,7 +125,7 @@ func (s *metadataSerializer) serializeParameterTypesOfNode(node *ast.Node, conta if i == 0 && ast.IsIdentifier(parameter.Name()) && parameter.Name().Text() == "this" { continue } - if parameter.AsParameterDeclaration().DotDotDotToken != nil { + if parameter.AsParameterDeclaration().DotDotDotToken() != nil { expressions = append(expressions, s.serializeTypeNode(ast.GetRestParameterElementType(parameter.Type()))) } else { expressions = append(expressions, s.serializeTypeOfNode(parameter, container)) @@ -138,7 +138,7 @@ func getParametersOfDecoratedDeclaration(node *ast.Node, container *ast.Node) *a if container != nil && node.Kind == ast.KindGetAccessor { acc := ast.GetAllAccessorDeclarations(container.Members(), node) if acc.SetAccessor != nil { - return acc.SetAccessor.Parameters + return acc.SetAccessor.Parameters() } } return node.ParameterList() @@ -190,7 +190,7 @@ func (s *metadataSerializer) serializeTypeNode(node *ast.Node) *ast.Node { case ast.KindArrayType, ast.KindTupleType: return s.f.NewIdentifier("Array") case ast.KindTypePredicate: - if node.AsTypePredicateNode().AssertsModifier != nil { + if node.AsTypePredicateNode().AssertsModifier() != nil { return s.f.NewVoidZeroExpression() } return s.f.NewIdentifier("Boolean") @@ -201,7 +201,7 @@ func (s *metadataSerializer) serializeTypeNode(node *ast.Node) *ast.Node { case ast.KindObjectKeyword: return s.f.NewIdentifier("Object") case ast.KindLiteralType: - return s.serializeLiteralOfLiteralTypeNode(node.AsLiteralTypeNode().Literal) + return s.serializeLiteralOfLiteralTypeNode(node.AsLiteralTypeNode().Literal()) case ast.KindNumberKeyword: return s.f.NewIdentifier("Number") case ast.KindBigIntKeyword: @@ -211,14 +211,14 @@ func (s *metadataSerializer) serializeTypeNode(node *ast.Node) *ast.Node { case ast.KindTypeReference: return s.serializeTypeReferenceNode(node.AsTypeReferenceNode()) case ast.KindIntersectionType: - return s.serializeUnionOrIntersectionConstituents(node.AsIntersectionTypeNode().Types.Nodes, true) + return s.serializeUnionOrIntersectionConstituents(node.AsIntersectionTypeNode().Types().Nodes, true) case ast.KindUnionType: - return s.serializeUnionOrIntersectionConstituents(node.AsUnionTypeNode().Types.Nodes, false) + return s.serializeUnionOrIntersectionConstituents(node.AsUnionTypeNode().Types().Nodes, false) case ast.KindConditionalType: oldState := s.c.serializingConditionalTypeBranch s.c.serializingConditionalTypeBranch = true defer func() { s.c.serializingConditionalTypeBranch = oldState }() - return s.serializeUnionOrIntersectionConstituents([]*ast.Node{node.AsConditionalTypeNode().TrueType, node.AsConditionalTypeNode().FalseType}, false) + return s.serializeUnionOrIntersectionConstituents([]*ast.Node{node.AsConditionalTypeNode().TrueType(), node.AsConditionalTypeNode().FalseType()}, false) case ast.KindTypeOperator: if node.AsTypeOperatorNode().Operator == ast.KindReadonlyKeyword { return s.serializeTypeNode(node.Type()) @@ -262,7 +262,7 @@ func (s *metadataSerializer) serializeUnionOrIntersectionConstituents(types []*a return s.f.NewIdentifier("Object") // Reduce to `any` in a union or intersection } - if !s.strictNullChecks && ((ast.IsLiteralTypeNode(typeNode) && typeNode.AsLiteralTypeNode().Literal.Kind == ast.KindNullKeyword) || typeNode.Kind == ast.KindUndefinedKeyword) { + if !s.strictNullChecks && ((ast.IsLiteralTypeNode(typeNode) && typeNode.AsLiteralTypeNode().Literal().Kind == ast.KindNullKeyword) || typeNode.Kind == ast.KindUndefinedKeyword) { continue // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } @@ -297,7 +297,7 @@ func (s *metadataSerializer) serializeLiteralOfLiteralTypeNode(node *ast.Node) * case ast.KindStringLiteral, ast.KindNoSubstitutionTemplateLiteral: return s.f.NewIdentifier("String") case ast.KindPrefixUnaryExpression: - operand := node.AsPrefixUnaryExpression().Operand + operand := node.AsPrefixUnaryExpression().Operand() switch operand.Kind { case ast.KindNumericLiteral, ast.KindBigIntLiteral: return s.serializeLiteralOfLiteralTypeNode(operand) @@ -328,7 +328,7 @@ func (s *metadataSerializer) serializeTypeReferenceNode(node *ast.TypeReferenceN if serialScope == nil { serialScope = s.c.currentLexicalScope } - kind := s.resolver.GetTypeReferenceSerializationKind(s.ec.ParseNode(node.TypeName), s.ec.ParseNode(serialScope)) + kind := s.resolver.GetTypeReferenceSerializationKind(s.ec.ParseNode(node.TypeName()), s.ec.ParseNode(serialScope)) switch kind { case printer.TypeReferenceSerializationKindUnknown: // From conditional type type reference that cannot be resolved is Similar to any or unknown @@ -336,7 +336,7 @@ func (s *metadataSerializer) serializeTypeReferenceNode(node *ast.TypeReferenceN return s.f.NewIdentifier("Object") } - serialized := s.serializeEntityNameAsExpressionFallback(node.TypeName) + serialized := s.serializeEntityNameAsExpressionFallback(node.TypeName()) temp := s.f.NewTempVariable() s.ec.AddVariableDeclaration(temp) return s.f.NewConditionalExpression( @@ -348,7 +348,7 @@ func (s *metadataSerializer) serializeTypeReferenceNode(node *ast.TypeReferenceN ) case printer.TypeReferenceSerializationKindTypeWithConstructSignatureAndValue: - return s.serializeEntityNameAsExpression(node.TypeName) + return s.serializeEntityNameAsExpression(node.TypeName()) case printer.TypeReferenceSerializationKindVoidNullableOrNeverType: return s.f.NewVoidZeroExpression() @@ -409,8 +409,8 @@ func (s *metadataSerializer) serializeEntityNameAsExpression(node *ast.EntityNam // a source tree node for the purposes of the checker. name := node.Clone(s.f) name.Loc = node.Loc - s.ec.UnsetOriginal(name) // make this identifier emulate a parse node, making it behave correctly when inspected by the module transforms - name.Parent = s.ec.ParseNode(s.c.currentLexicalScope) //nolint:customlint // ensure the parent is set to a parse tree node. + s.ec.UnsetOriginal(name) // make this identifier emulate a parse node, making it behave correctly when inspected by the module transforms + name.SetParent(s.ec.ParseNode(s.c.currentLexicalScope)) //nolint:customlint // ensure the parent is set to a parse tree node. return name case ast.KindQualifiedName: return s.serializeQualifiedNameAsExpression(node.AsQualifiedName()) @@ -423,7 +423,7 @@ func (s *metadataSerializer) serializeEntityNameAsExpression(node *ast.EntityNam * @param node The qualified name to serialize. */ func (s *metadataSerializer) serializeQualifiedNameAsExpression(node *ast.QualifiedName) *ast.Node { - return s.f.NewPropertyAccessExpression(s.serializeEntityNameAsExpression(node.Left), nil, node.Right, ast.NodeFlagsNone) + return s.f.NewPropertyAccessExpression(s.serializeEntityNameAsExpression(node.Left()), nil, node.Right(), ast.NodeFlagsNone) } /** @@ -436,20 +436,20 @@ func (s *metadataSerializer) serializeEntityNameAsExpressionFallback(node *ast.E copied := s.serializeEntityNameAsExpression(node) return s.createCheckedValue(copied, copied) } - if node.AsQualifiedName().Left.Kind == ast.KindIdentifier { + if node.AsQualifiedName().Left().Kind == ast.KindIdentifier { // A.B -> typeof A !== "undefined" && A.B - return s.createCheckedValue(s.serializeEntityNameAsExpression(node.AsQualifiedName().Left), s.serializeEntityNameAsExpression(node)) + return s.createCheckedValue(s.serializeEntityNameAsExpression(node.AsQualifiedName().Left()), s.serializeEntityNameAsExpression(node)) } // A.B.C -> typeof A !== "undefined" && (_a = A.B) !== void 0 && _a.C - left := s.serializeEntityNameAsExpressionFallback(node.AsQualifiedName().Left) + left := s.serializeEntityNameAsExpressionFallback(node.AsQualifiedName().Left()) temp := s.f.NewTempVariable() s.ec.AddVariableDeclaration(temp) return s.f.NewLogicalANDExpression( s.f.NewLogicalANDExpression( - left.AsBinaryExpression().Left, - s.f.NewStrictInequalityExpression(s.f.NewAssignmentExpression(temp, left.AsBinaryExpression().Right), s.f.NewVoidZeroExpression()), + left.AsBinaryExpression().Left(), + s.f.NewStrictInequalityExpression(s.f.NewAssignmentExpression(temp, left.AsBinaryExpression().Right()), s.f.NewVoidZeroExpression()), ), - s.f.NewPropertyAccessExpression(temp, nil, node.AsQualifiedName().Right, ast.NodeFlagsNone), + s.f.NewPropertyAccessExpression(temp, nil, node.AsQualifiedName().Right(), ast.NodeFlagsNone), ) } @@ -501,11 +501,11 @@ func (s *metadataSerializer) equateSerializedTypeNodes(left *ast.Node, right *as } // conditionals used in fallback if ast.IsConditionalExpression(left) { - return ast.IsConditionalExpression(right) && s.equateSerializedTypeNodes(left.AsConditionalExpression().Condition, right.AsConditionalExpression().Condition) && s.equateSerializedTypeNodes(left.AsConditionalExpression().WhenTrue, right.AsConditionalExpression().WhenTrue) && s.equateSerializedTypeNodes(left.AsConditionalExpression().WhenFalse, right.AsConditionalExpression().WhenFalse) + return ast.IsConditionalExpression(right) && s.equateSerializedTypeNodes(left.AsConditionalExpression().Condition(), right.AsConditionalExpression().Condition()) && s.equateSerializedTypeNodes(left.AsConditionalExpression().WhenTrue(), right.AsConditionalExpression().WhenTrue()) && s.equateSerializedTypeNodes(left.AsConditionalExpression().WhenFalse(), right.AsConditionalExpression().WhenFalse()) } // logical binary and assignments used in fallback if ast.IsBinaryExpression(left) { - return ast.IsBinaryExpression(right) && left.AsBinaryExpression().OperatorToken.Kind == right.AsBinaryExpression().OperatorToken.Kind && s.equateSerializedTypeNodes(left.AsBinaryExpression().Left, right.AsBinaryExpression().Left) && s.equateSerializedTypeNodes(left.AsBinaryExpression().Right, right.AsBinaryExpression().Right) + return ast.IsBinaryExpression(right) && left.AsBinaryExpression().OperatorToken().Kind == right.AsBinaryExpression().OperatorToken().Kind && s.equateSerializedTypeNodes(left.AsBinaryExpression().Left(), right.AsBinaryExpression().Left()) && s.equateSerializedTypeNodes(left.AsBinaryExpression().Right(), right.AsBinaryExpression().Right()) } return false } diff --git a/tsc/internal/transformers/utilities.go b/tsc/internal/transformers/utilities.go index af826b85a6c20..a3daed4481afb 100644 --- a/tsc/internal/transformers/utilities.go +++ b/tsc/internal/transformers/utilities.go @@ -78,30 +78,30 @@ func IsIdentifierReference(name *ast.IdentifierNode, parent *ast.Node) bool { // only an `Initializer()` child that can be `Identifier` would be an instance of `IdentifierReference` return parent.Initializer() == name case ast.KindShorthandPropertyAssignment: - return parent.AsShorthandPropertyAssignment().ObjectAssignmentInitializer == name + return parent.AsShorthandPropertyAssignment().ObjectAssignmentInitializer() == name case ast.KindForStatement: return parent.Initializer() == name || - parent.AsForStatement().Condition == name || - parent.AsForStatement().Incrementor == name + parent.AsForStatement().Condition() == name || + parent.AsForStatement().Incrementor() == name case ast.KindForInStatement, ast.KindForOfStatement: return parent.Initializer() == name || parent.Expression() == name case ast.KindImportEqualsDeclaration: - return parent.AsImportEqualsDeclaration().ModuleReference == name + return parent.AsImportEqualsDeclaration().ModuleReference() == name case ast.KindArrowFunction: return parent.Body() == name case ast.KindConditionalExpression: - return parent.AsConditionalExpression().Condition == name || - parent.AsConditionalExpression().WhenTrue == name || - parent.AsConditionalExpression().WhenFalse == name + return parent.AsConditionalExpression().Condition() == name || + parent.AsConditionalExpression().WhenTrue() == name || + parent.AsConditionalExpression().WhenFalse() == name case ast.KindCallExpression, ast.KindNewExpression: return parent.Expression() == name || slices.Contains(parent.Arguments(), name) case ast.KindTaggedTemplateExpression: - return parent.AsTaggedTemplateExpression().Tag == name + return parent.AsTaggedTemplateExpression().Tag() == name case ast.KindImportAttribute: - return parent.AsImportAttribute().Value == name + return parent.AsImportAttribute().Value() == name case ast.KindJsxOpeningElement, ast.KindJsxClosingElement: return parent.TagName() == name default: @@ -117,14 +117,14 @@ func convertBindingElementToArrayAssignmentElement(emitContext *printer.EmitCont return elision } expression := convertBindingNameToAssignmentElementTarget(emitContext, element.Name()) - if element.DotDotDotToken != nil { + if element.DotDotDotToken() != nil { spread := emitContext.Factory.NewSpreadElement(expression) emitContext.SetOriginal(spread, element.AsNode()) emitContext.AssignCommentAndSourceMapRanges(spread, element.AsNode()) return spread } - if element.Initializer != nil { - assignment := emitContext.Factory.NewAssignmentExpression(expression, element.Initializer) + if element.Initializer() != nil { + assignment := emitContext.Factory.NewAssignmentExpression(expression, element.Initializer()) emitContext.SetOriginal(assignment, element.AsNode()) emitContext.AssignCommentAndSourceMapRanges(assignment, element.AsNode()) return assignment @@ -133,24 +133,24 @@ func convertBindingElementToArrayAssignmentElement(emitContext *printer.EmitCont } func convertBindingElementToObjectAssignmentElement(emitContext *printer.EmitContext, element *ast.BindingElement) *ast.ObjectLiteralElement { - if element.DotDotDotToken != nil { + if element.DotDotDotToken() != nil { spread := emitContext.Factory.NewSpreadAssignment(element.Name()) emitContext.SetOriginal(spread, element.AsNode()) emitContext.AssignCommentAndSourceMapRanges(spread, element.AsNode()) return spread } - if element.PropertyName != nil { + if element.PropertyName() != nil { expression := convertBindingNameToAssignmentElementTarget(emitContext, element.Name()) - if element.Initializer != nil { - expression = emitContext.Factory.NewAssignmentExpression(expression, element.Initializer) + if element.Initializer() != nil { + expression = emitContext.Factory.NewAssignmentExpression(expression, element.Initializer()) } - assignment := emitContext.Factory.NewPropertyAssignment(nil /*modifiers*/, element.PropertyName, nil /*postfixToken*/, nil /*typeNode*/, expression) + assignment := emitContext.Factory.NewPropertyAssignment(nil /*modifiers*/, element.PropertyName(), nil /*postfixToken*/, nil /*typeNode*/, expression) emitContext.SetOriginal(assignment, element.AsNode()) emitContext.AssignCommentAndSourceMapRanges(assignment, element.AsNode()) return assignment } var equalsToken *ast.TokenNode - if element.Initializer != nil { + if element.Initializer() != nil { equalsToken = emitContext.Factory.NewToken(ast.KindEqualsToken) } assignment := emitContext.Factory.NewShorthandPropertyAssignment( @@ -159,7 +159,7 @@ func convertBindingElementToObjectAssignmentElement(emitContext *printer.EmitCon nil, /*postfixToken*/ nil, /*typeNode*/ equalsToken, - element.Initializer, + element.Initializer(), ) emitContext.SetOriginal(assignment, element.AsNode()) emitContext.AssignCommentAndSourceMapRanges(assignment, element.AsNode()) @@ -179,11 +179,11 @@ func ConvertBindingPatternToAssignmentPattern(emitContext *printer.EmitContext, func convertBindingElementToObjectAssignmentPattern(emitContext *printer.EmitContext, element *ast.BindingPattern) *ast.Expression { var properties []*ast.ObjectLiteralElement - for _, element := range element.Elements.Nodes { + for _, element := range element.Elements().Nodes { properties = append(properties, convertBindingElementToObjectAssignmentElement(emitContext, element.AsBindingElement())) } propertyList := emitContext.Factory.NewNodeList(properties) - propertyList.Loc = element.Elements.Loc + propertyList.Loc = element.Elements().Loc object := emitContext.Factory.NewObjectLiteralExpression(propertyList, false /*multiLine*/) emitContext.SetOriginal(object, element.AsNode()) emitContext.AssignCommentAndSourceMapRanges(object, element.AsNode()) @@ -192,11 +192,11 @@ func convertBindingElementToObjectAssignmentPattern(emitContext *printer.EmitCon func convertBindingElementToArrayAssignmentPattern(emitContext *printer.EmitContext, element *ast.BindingPattern) *ast.Expression { var elements []*ast.Expression - for _, element := range element.Elements.Nodes { + for _, element := range element.Elements().Nodes { elements = append(elements, convertBindingElementToArrayAssignmentElement(emitContext, element.AsBindingElement())) } elementList := emitContext.Factory.NewNodeList(elements) - elementList.Loc = element.Elements.Loc + elementList.Loc = element.Elements().Loc object := emitContext.Factory.NewArrayLiteralExpression(elementList, false /*multiLine*/) emitContext.SetOriginal(object, element.AsNode()) emitContext.AssignCommentAndSourceMapRanges(object, element.AsNode()) @@ -211,11 +211,11 @@ func convertBindingNameToAssignmentElementTarget(emitContext *printer.EmitContex } func ConvertVariableDeclarationToAssignmentExpression(emitContext *printer.EmitContext, element *ast.VariableDeclaration) *ast.Expression { - if element.Initializer == nil { + if element.Initializer() == nil { return nil } expression := convertBindingNameToAssignmentElementTarget(emitContext, element.Name()) - assignment := emitContext.Factory.NewAssignmentExpression(expression, element.Initializer) + assignment := emitContext.Factory.NewAssignmentExpression(expression, element.Initializer()) emitContext.SetOriginal(assignment, element.AsNode()) emitContext.AssignCommentAndSourceMapRanges(assignment, element.AsNode()) return assignment @@ -284,7 +284,7 @@ func findSuperStatementIndexPathWorker(statements []*ast.Statement, start int, i if GetSuperCallFromStatement(statement) != nil { return append(indices, i) } else if ast.IsTryStatement(statement) { - if result := findSuperStatementIndexPathWorker(statement.AsTryStatement().TryBlock.Statements(), 0, indices); result != nil { + if result := findSuperStatementIndexPathWorker(statement.AsTryStatement().TryBlock().Statements(), 0, indices); result != nil { return append(result, i) } } diff --git a/tsc/internal/tsoptions/tsconfigparsing.go b/tsc/internal/tsoptions/tsconfigparsing.go index 4241f27529dd2..23bd3b140da1d 100644 --- a/tsc/internal/tsoptions/tsconfigparsing.go +++ b/tsc/internal/tsoptions/tsconfigparsing.go @@ -123,7 +123,7 @@ func parseOwnConfigOfJsonSourceFile( // Ensure value is verified except for extends which is handled in its own way for error reporting var propertySetErrors []*ast.Diagnostic if option != nil && option != extendsOptionDeclaration { - value, propertySetErrors = convertJsonOption(option, value, basePath, propertyAssignment, propertyAssignment.Initializer, sourceFile) + value, propertySetErrors = convertJsonOption(option, value, basePath, propertyAssignment, propertyAssignment.Initializer(), sourceFile) } if parentOption != nil && parentOption.Name != "undefined" && value != nil { if option != nil && option.Name != "" { @@ -166,7 +166,7 @@ func parseOwnConfigOfJsonSourceFile( } } else if parentOption == tsconfigRootOptionsMap { if option == extendsOptionDeclaration { - configPath, err := getExtendsConfigPathOrArray(value, fs, basePath, configFileName, propertyAssignment, propertyAssignment.Initializer, sourceFile) + configPath, err := getExtendsConfigPathOrArray(value, fs, basePath, configFileName, propertyAssignment, propertyAssignment.Initializer(), sourceFile) extendedConfigPaths = configPath propertySetErrors = append(propertySetErrors, err...) } else if option == nil { @@ -649,7 +649,7 @@ func convertObjectLiteralExpressionToJson( result = &collections.OrderedMap[string, any]{} } var errors []*ast.Diagnostic - for _, element := range node.Properties.Nodes { + for _, element := range node.Properties().Nodes { if element.Kind != ast.KindPropertyAssignment { errors = append(errors, ast.NewDiagnostic(sourceFile, element.Loc, diagnostics.Property_assignment_expected)) continue @@ -670,7 +670,7 @@ func convertObjectLiteralExpressionToJson( option = nil } } - value, err := convertPropertyValueToJson(sourceFile, element.AsPropertyAssignment().Initializer, option, returnValue, jsonConversionNotifier) + value, err := convertPropertyValueToJson(sourceFile, element.AsPropertyAssignment().Initializer(), option, returnValue, jsonConversionNotifier) errors = append(errors, err...) if keyText != "" { if returnValue { @@ -731,10 +731,10 @@ func convertPropertyValueToJson(sourceFile *ast.SourceFile, valueExpression *ast case ast.KindNumericLiteral: return float64(jsnum.FromString(valueExpression.Text())), nil case ast.KindPrefixUnaryExpression: - if valueExpression.AsPrefixUnaryExpression().Operator != ast.KindMinusToken || valueExpression.AsPrefixUnaryExpression().Operand.Kind != ast.KindNumericLiteral { + if valueExpression.AsPrefixUnaryExpression().Operator != ast.KindMinusToken || valueExpression.AsPrefixUnaryExpression().Operand().Kind != ast.KindNumericLiteral { break // not valid JSON syntax } - return float64(-jsnum.FromString(valueExpression.AsPrefixUnaryExpression().Operand.Text())), nil + return float64(-jsnum.FromString(valueExpression.AsPrefixUnaryExpression().Operand().Text())), nil case ast.KindObjectLiteralExpression: objectLiteralExpression := valueExpression.AsObjectLiteralExpression() // Currently having element option declaration in the tsconfig with type "object" @@ -1179,7 +1179,7 @@ func parseJsonConfigFileContentWorker( fileName = "tsconfig.json" } diagnosticMessage := diagnostics.The_files_list_in_config_file_0_is_empty - nodeValue := ForEachTsConfigPropArray(sourceFile.SourceFile, "files", func(property *ast.PropertyAssignment) *ast.Node { return property.Initializer }) + nodeValue := ForEachTsConfigPropArray(sourceFile.SourceFile, "files", func(property *ast.PropertyAssignment) *ast.Node { return property.Initializer() }) errors = append(errors, CreateDiagnosticForNodeInSourceFile(sourceFile.SourceFile, nodeValue, diagnosticMessage, fileName)) } else { errors = append(errors, ast.NewCompilerDiagnostic(diagnostics.The_files_list_in_config_file_0_is_empty, configFileName)) @@ -1531,8 +1531,8 @@ func CreateDiagnosticAtReferenceSyntax(config *ParsedCommandLine, index int, mes return nil } return ForEachTsConfigPropArray(config.ConfigFile.SourceFile, "references", func(property *ast.PropertyAssignment) *ast.Diagnostic { - if ast.IsArrayLiteralExpression(property.Initializer) { - value := property.Initializer.Elements() + if ast.IsArrayLiteralExpression(property.Initializer()) { + value := property.Initializer().Elements() if len(value) > index { return CreateDiagnosticForNodeInSourceFile(config.ConfigFile.SourceFile, value[index], message, args...) } @@ -1545,11 +1545,11 @@ func createDiagnosticAtProjectReferenceProperty(sourceFile *TsConfigSourceFile, var node *ast.Node if sourceFile != nil { node = ForEachTsConfigPropArray(sourceFile.SourceFile, "references", func(property *ast.PropertyAssignment) *ast.Node { - if ast.IsArrayLiteralExpression(property.Initializer) { - elements := property.Initializer.Elements() + if ast.IsArrayLiteralExpression(property.Initializer()) { + elements := property.Initializer().Elements() if len(elements) > index && ast.IsObjectLiteralExpression(elements[index]) { if propertyNode := ForEachPropertyAssignment(elements[index].AsObjectLiteralExpression(), propertyName, func(property *ast.PropertyAssignment) *ast.Node { - return property.Initializer + return property.Initializer() }); propertyNode != nil { return propertyNode } @@ -1564,8 +1564,8 @@ func createDiagnosticAtProjectReferenceProperty(sourceFile *TsConfigSourceFile, func GetCallbackForFindingPropertyAssignmentByValue(value string) func(property *ast.PropertyAssignment) *ast.Node { return func(property *ast.PropertyAssignment) *ast.Node { - if ast.IsArrayLiteralExpression(property.Initializer) { - return core.Find(property.Initializer.Elements(), func(element *ast.Node) bool { + if ast.IsArrayLiteralExpression(property.Initializer()) { + return core.Find(property.Initializer().Elements(), func(element *ast.Node) bool { return ast.IsStringLiteral(element) && element.Text() == value }) } @@ -1586,17 +1586,17 @@ func getContentMapperSyntax(sourceFile *ast.SourceFile, index int, subKey string return nil } return ForEachTsConfigPropArray(sourceFile, "contentMappers", func(property *ast.PropertyAssignment) *ast.Node { - if !ast.IsArrayLiteralExpression(property.Initializer) { - return property.Initializer + if !ast.IsArrayLiteralExpression(property.Initializer()) { + return property.Initializer() } - elements := property.Initializer.Elements() + elements := property.Initializer().Elements() if index < 0 || index >= len(elements) { - return property.Initializer + return property.Initializer() } element := elements[index] if subKey != "" && ast.IsObjectLiteralExpression(element) { if node := ForEachPropertyAssignment(element.AsObjectLiteralExpression(), subKey, func(property *ast.PropertyAssignment) *ast.Node { - return property.Initializer + return property.Initializer() }); node != nil { return node } @@ -1625,7 +1625,7 @@ func GetContentMapperOptionDiagnosticLocation(config *ParsedCommandLine, mapper } case !segment.IsIndex && ast.IsObjectLiteralExpression(node): next = ForEachPropertyAssignment(node.AsObjectLiteralExpression(), segment.Property, func(property *ast.PropertyAssignment) *ast.Node { - return property.Initializer + return property.Initializer() }) } if next == nil { @@ -1678,7 +1678,7 @@ func setContentMapperDiagnosticLocation(diagnostic *ast.Diagnostic, sourceFile * func ForEachPropertyAssignment[T any](objectLiteral *ast.ObjectLiteralExpression, key string, callback func(property *ast.PropertyAssignment) *T, key2 ...string) *T { if objectLiteral != nil { - for _, property := range objectLiteral.Properties.Nodes { + for _, property := range objectLiteral.Properties().Nodes { if !ast.IsPropertyAssignment(property) { continue } From a9c7ad81ca0832dd676955387057c2286dc47c2e Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 8 Oct 2026 07:11:38 +0000 Subject: [PATCH 2/2] Enhance arena memory management with progress tracking in NodeFactory - Updated StartParse to accept progress tracking for memory allocation. - Introduced TrackProgress method in Arena to adjust memory estimates based on parsing progress. - Added FinishParse to finalize progress tracking. - Enhanced tests to validate new progress tracking functionality. --- tsc/internal/ast/arena.go | 17 +++- tsc/internal/linkarena/linkarena.go | 60 ++++++++++--- tsc/internal/linkarena/linkarena_test.go | 108 ++++++++++++++++++++--- tsc/internal/parser/parser.go | 11 ++- 4 files changed, 165 insertions(+), 31 deletions(-) diff --git a/tsc/internal/ast/arena.go b/tsc/internal/ast/arena.go index fed5f5d98f101..837dda6963104 100644 --- a/tsc/internal/ast/arena.go +++ b/tsc/internal/ast/arena.go @@ -129,15 +129,24 @@ func newParseArena(sourceText string, sizeHint int) *linkarena.Arena { } // StartParse readies the factory for building the syntax tree of sourceText in a new arena. -// Until the factory is reset, every node placed in a node list must have been created by it. -func (f *NodeFactory) StartParse(sourceText string) { - // A syntax tree takes several times the size of its text. A low estimate costs little: - // the arena grows in small steps once the estimate is used up. +// progress reports how much of the text has been parsed; the arena uses it to avoid holding +// much more memory than the tree turns out to need. FinishParse must be called when the tree +// is complete. Until the factory is reset, every node placed in a node list must have been +// created by it. +func (f *NodeFactory) StartParse(sourceText string, progress linkarena.Progress) { + // A syntax tree takes several times the size of its text. This first estimate only + // decides the size of the first chunk, and a low one costs little. f.arena = newParseArena(sourceText, len(sourceText)*5) + f.arena.TrackProgress(progress) f.parsing = true f.sourceText = sourceText } +// FinishParse ends what StartParse began. +func (f *NodeFactory) FinishParse() { + f.arena.TrackProgress(nil) +} + // StartLazyJSDocParse readies the factory for parsing a JSDoc comment of file on demand. // All such comments of a file share one arena; a comment is far smaller than the smallest // arena. The caller holds the lock that guards the file's JSDoc cache. diff --git a/tsc/internal/linkarena/linkarena.go b/tsc/internal/linkarena/linkarena.go index e92fd0eba159d..969eea70e26f4 100644 --- a/tsc/internal/linkarena/linkarena.go +++ b/tsc/internal/linkarena/linkarena.go @@ -158,10 +158,12 @@ type Arena struct { chunkBase unsafe.Pointer chunkSize uintptr pagesLeft int - // The number of bytes the owner still expects to allocate, used to size chunks. + // The number of bytes the owner is still expected to allocate, used to size chunks. hint int - // The number of pages in the most recent chunk allocated beyond the hint. - grown int + // When set, the expectation is derived from the owner's progress each time the arena + // grows. done is the furthest progress reported so far. + progress Progress + done int // Every chunk of the arena, and their address ranges in sorted order. chunks []unsafe.Pointer @@ -189,6 +191,25 @@ func NewArena(sizeHint int) *Arena { return a } +// Progress reports how far the owner of an arena is through the work it allocates for. +type Progress interface { + // Progress returns how much of the owner's input has been consumed and the size of the + // whole input, in the same unit. + Progress() (done int, total int) +} + +// TrackProgress makes the arena derive how much more its owner will allocate from the +// owner's progress: the rest of the input is taken to need as much memory per unit as the +// part consumed so far. The estimate given to NewArena then only sizes the first chunk. The +// owner must pass nil when it is finished, because the arena outlives it. +func (a *Arena) TrackProgress(progress Progress) { + a.progress = progress + a.done = 0 + if progress == nil { + a.hint = 0 + } +} + // Alloc returns size bytes of zeroed memory aligned to 8 bytes. size must not exceed // MaxAlloc. func (a *Arena) Alloc(size uintptr) unsafe.Pointer { @@ -223,19 +244,30 @@ func (a *Arena) allocSlow(size uintptr) unsafe.Pointer { // grow adds a chunk to the arena. func (a *Arena) grow() { - // Chunks are as large as the owner's estimate allows, so that little is left unused when - // the estimate is right. Beyond the estimate, chunk sizes double. - n := 1 - if a.hint >= pageSize { - n = min(a.hint>>pageShift, maxChunkPages) - n = 1 << (bitLen(uint(n)) - 1) - } else { - if a.grown > 0 { - n = min(a.grown*2, maxChunkPages) + // The unused end of an arena's last chunk stays allocated for as long as the arena, so a + // chunk is never larger than what the owner is still expected to allocate. + if a.progress != nil && a.size > 0 { + done, total := a.progress.Progress() + // Owners that work speculatively can report less progress than they did before. + a.done = max(a.done, done) + if a.done > 0 { + // Only whether the largest chunk is still warranted matters. + expected := float64(a.size) * float64(max(total-a.done, 0)) / float64(a.done) + a.hint = int(min(expected, maxChunkPages*pageSize)) } - a.grown = n } - a.hint -= n << pageShift + n := 1 + switch { + case a.hint >= pageSize: + n = a.hint >> pageShift + case a.progress == nil: + // Nothing is known about what is to come: grow by at most a quarter of what the + // arena holds, which keeps large arenas from growing a page at a time. + n = max(a.size>>(pageShift+2), 1) + } + // Chunks come in sizes of 1, 2, 4 and 8 pages. + n = 1 << (bitLen(uint(min(n, maxChunkPages))) - 1) + a.hint = max(a.hint-n<