diff --git a/_tools/customlint/plugin.go b/_tools/customlint/plugin.go index d8e8a8365d..42f381f04d 100644 --- a/_tools/customlint/plugin.go +++ b/_tools/customlint/plugin.go @@ -17,6 +17,7 @@ func (f *plugin) BuildAnalyzers() ([]*analysis.Analyzer, error) { return []*analysis.Analyzer{ emptyCaseAnalyzer, shadowAnalyzer, + unexportedAPIAnalyzer, }, nil } diff --git a/_tools/customlint/testdata/shadow/shadow.go.golden b/_tools/customlint/testdata/shadow/shadow.go.golden index 4273805b91..9f390fc1b9 100644 --- a/_tools/customlint/testdata/shadow/shadow.go.golden +++ b/_tools/customlint/testdata/shadow/shadow.go.golden @@ -62,6 +62,8 @@ type isType int func F5() isType { + ~ +!!! unexportedapi: exported API references unexported identifier isType var isType isType // OK return isType } @@ -69,6 +71,8 @@ type isAlias int func F6() isAlias { + ~ +!!! unexportedapi: exported API references unexported identifier isAlias var isAlias isAlias // OK return isAlias } diff --git a/_tools/customlint/testdata/unexportedapi/unexportedapi.go b/_tools/customlint/testdata/unexportedapi/unexportedapi.go new file mode 100644 index 0000000000..c84fd2edb1 --- /dev/null +++ b/_tools/customlint/testdata/unexportedapi/unexportedapi.go @@ -0,0 +1,211 @@ +package unexportedapi + +type Foo struct { + Bar *oops +} + +type oops struct { + v int +} + +type Okay struct { + Sure int + Value ***Okay2 +} + +type Okay2 struct { + VeryGood struct{} +} + +func OkayFunc(v *Okay) *Okay2 { + if v == nil { + return nil + } + return **v.Value +} + +// Test cases for various scenarios + +// Exported function with unexported parameter type +func BadFunc(x unexported) {} + +// Exported function with unexported return type +func AnotherBadFunc() *unexported { + return nil +} + +// Exported function with unexported type in slice +func SliceFunc(x []unexported) {} + +// Exported function with unexported type in map +func MapFunc(x map[string]unexported) {} + +// Exported function with unexported type in map key +func MapKeyFunc(x map[unexported]string) {} + +// Exported function with unexported type in channel +func ChanFunc(x chan unexported) {} + +// Exported type alias to unexported type +type BadAlias = unexported + +// Exported type with unexported embedded field (OK since unexported has no exported members) +type OkayEmbed struct { + unexported +} + +// Unexported type with exported field +type unexportedWithExportedField struct { + ExportedField int +} + +// Bad - exported type embedding unexported type with exported members +type BadEmbed struct { + unexportedWithExportedField +} + +// Unexported type - should not trigger +type okayUnexported struct { + field unexported +} + +// Exported interface with unexported type in method +type BadInterface interface { + Method(x unexported) +} + +// Exported interface with unexported return type +type AnotherBadInterface interface { + Method() unexported +} + +type unexported struct { + x int +} + +// Exported function with multiple return values including unexported +func MultiReturn() (int, unexported, error) { + return 0, unexported{}, nil +} + +// Exported variable with unexported type +var BadVar unexported + +// Exported const with unexported type (should not be possible, but let's be safe) +// const BadConst unexported = unexported{} // This won't compile anyway + +// Array of unexported type +type BadArray [10]unexported + +// Exported function with variadic unexported parameter +func VariadicFunc(args ...unexported) {} + +// Exported type with method returning unexported type +type ExportedWithMethod struct{} + +func (e ExportedWithMethod) Method() unexported { + return unexported{} +} + +// Exported type with pointer receiver method returning unexported type +func (e *ExportedWithMethod) PointerMethod() *unexported { + return nil +} + +// Generic type with unexported type constraint (Go 1.18+) +type GenericExported[T any] struct { + Value T +} + +// Okay - unexported method on exported type (methods are not part of exported API unless on exported interface) +func (e ExportedWithMethod) unexportedMethod() unexported { + return unexported{} +} + +// Test variables initialized with function calls + +// Helper functions for testing +func helperReturnsExported() *Okay2 { + return &Okay2{} +} + +func helperReturnsUnexported() unexported { + return unexported{} +} + +// Okay - exported variable initialized by calling unexported function that returns exported type +var OkayVarFromUnexportedFunc = helperReturnsExported() + +// Bad - exported variable initialized by calling exported function that returns unexported type +var BadVarFromFunc = helperReturnsUnexported() + +// Okay - exported variable with explicit type (implementation doesn't matter) +var OkayVarExplicitType *Okay2 = helperReturnsExported() + +// Bad - exported variable with explicit unexported type +var BadVarExplicitType unexported = helperReturnsUnexported() + +// Test type aliases +type ( + ExportedString string + unexportedString string +) + +// Okay - exported function using exported type alias +func OkayTypeAlias(s ExportedString) {} + +// Bad - exported function using unexported type alias +func BadTypeAlias(s unexportedString) {} + +// Test unexported types with exported methods (for interface satisfaction) +type unexportedImpl struct { + value int +} + +// Okay - exported method on unexported type (not part of public API, often used for interface satisfaction) +func (u *unexportedImpl) ExportedMethod() int { + return u.value +} + +// Okay - exported method on unexported type can return unexported types +func (u *unexportedImpl) AnotherMethod() unexported { + return unexported{} +} + +// Test for avoiding duplicate errors on embedded types with methods + +type BaseWithBadMethod struct{} + +// This method has an unexported return type - should be flagged once +func (b *BaseWithBadMethod) GetUnexported() *unexported { + return nil +} + +// This type embeds BaseWithBadMethod - should NOT re-report the GetUnexported method issue +type DerivedEmbedding struct { + BaseWithBadMethod +} + +// Test embedding unexported type with exported method that references unexported type +type unexportedBase struct{} + +// This exported method on unexported type won't be checked (unexported type methods are skipped) +func (u *unexportedBase) MethodWithBadReturn() *unexported { + return nil +} + +// This embeds an unexported type - what happens? +// OK because methods on unexported types aren't checked +type EmbeddingUnexportedBase struct { + unexportedBase +} + +// Test embedding unexported type with exported field that references unexported type +type unexportedBaseWithField struct { + ExportedField *unexported +} + +// Bad - embeds unexported type with exported field that references unexported type +type EmbeddingUnexportedBaseWithField struct { + unexportedBaseWithField +} diff --git a/_tools/customlint/testdata/unexportedapi/unexportedapi.go.golden b/_tools/customlint/testdata/unexportedapi/unexportedapi.go.golden new file mode 100644 index 0000000000..1c4c011a4f --- /dev/null +++ b/_tools/customlint/testdata/unexportedapi/unexportedapi.go.golden @@ -0,0 +1,256 @@ + package unexportedapi + + type Foo struct { + Bar *oops + ~ +!!! unexportedapi: exported API references unexported identifier oops + } + + type oops struct { + v int + } + + type Okay struct { + Sure int + Value ***Okay2 + } + + type Okay2 struct { + VeryGood struct{} + } + + func OkayFunc(v *Okay) *Okay2 { + if v == nil { + return nil + } + return **v.Value + } + + // Test cases for various scenarios + + // Exported function with unexported parameter type + func BadFunc(x unexported) {} + ~ +!!! unexportedapi: exported API references unexported identifier unexported + + // Exported function with unexported return type + func AnotherBadFunc() *unexported { + ~ +!!! unexportedapi: exported API references unexported identifier unexported + return nil + } + + // Exported function with unexported type in slice + func SliceFunc(x []unexported) {} + ~ +!!! unexportedapi: exported API references unexported identifier unexported + + // Exported function with unexported type in map + func MapFunc(x map[string]unexported) {} + ~ +!!! unexportedapi: exported API references unexported identifier unexported + + // Exported function with unexported type in map key + func MapKeyFunc(x map[unexported]string) {} + ~ +!!! unexportedapi: exported API references unexported identifier unexported + + // Exported function with unexported type in channel + func ChanFunc(x chan unexported) {} + ~ +!!! unexportedapi: exported API references unexported identifier unexported + + // Exported type alias to unexported type + type BadAlias = unexported + ~ +!!! unexportedapi: exported API references unexported identifier unexported + + // Exported type with unexported embedded field (OK since unexported has no exported members) + type OkayEmbed struct { + unexported + } + + // Unexported type with exported field + type unexportedWithExportedField struct { + ExportedField int + } + + // Bad - exported type embedding unexported type with exported members + type BadEmbed struct { + unexportedWithExportedField + } + + // Unexported type - should not trigger + type okayUnexported struct { + field unexported + } + + // Exported interface with unexported type in method + type BadInterface interface { + Method(x unexported) + ~ +!!! unexportedapi: exported API references unexported identifier unexported + } + + // Exported interface with unexported return type + type AnotherBadInterface interface { + Method() unexported + ~ +!!! unexportedapi: exported API references unexported identifier unexported + } + + type unexported struct { + x int + } + + // Exported function with multiple return values including unexported + func MultiReturn() (int, unexported, error) { + ~ +!!! unexportedapi: exported API references unexported identifier unexported + return 0, unexported{}, nil + } + + // Exported variable with unexported type + var BadVar unexported + ~ +!!! unexportedapi: exported API references unexported identifier unexported + + // Exported const with unexported type (should not be possible, but let's be safe) + // const BadConst unexported = unexported{} // This won't compile anyway + + // Array of unexported type + type BadArray [10]unexported + ~ +!!! unexportedapi: exported API references unexported identifier unexported + + // Exported function with variadic unexported parameter + func VariadicFunc(args ...unexported) {} + ~ +!!! unexportedapi: exported API references unexported identifier unexported + + // Exported type with method returning unexported type + type ExportedWithMethod struct{} + + func (e ExportedWithMethod) Method() unexported { + ~ +!!! unexportedapi: exported API references unexported identifier unexported + return unexported{} + } + + // Exported type with pointer receiver method returning unexported type + func (e *ExportedWithMethod) PointerMethod() *unexported { + ~ +!!! unexportedapi: exported API references unexported identifier unexported + return nil + } + + // Generic type with unexported type constraint (Go 1.18+) + type GenericExported[T any] struct { + Value T + } + + // Okay - unexported method on exported type (methods are not part of exported API unless on exported interface) + func (e ExportedWithMethod) unexportedMethod() unexported { + return unexported{} + } + + // Test variables initialized with function calls + + // Helper functions for testing + func helperReturnsExported() *Okay2 { + return &Okay2{} + } + + func helperReturnsUnexported() unexported { + return unexported{} + } + + // Okay - exported variable initialized by calling unexported function that returns exported type + var OkayVarFromUnexportedFunc = helperReturnsExported() + + // Bad - exported variable initialized by calling exported function that returns unexported type + var BadVarFromFunc = helperReturnsUnexported() + ~ +!!! unexportedapi: exported API references unexported type unexported + + // Okay - exported variable with explicit type (implementation doesn't matter) + var OkayVarExplicitType *Okay2 = helperReturnsExported() + + // Bad - exported variable with explicit unexported type + var BadVarExplicitType unexported = helperReturnsUnexported() + ~ +!!! unexportedapi: exported API references unexported identifier unexported + + // Test type aliases + type ( + ExportedString string + unexportedString string + ) + + // Okay - exported function using exported type alias + func OkayTypeAlias(s ExportedString) {} + + // Bad - exported function using unexported type alias + func BadTypeAlias(s unexportedString) {} + ~ +!!! unexportedapi: exported API references unexported identifier unexportedString + + // Test unexported types with exported methods (for interface satisfaction) + type unexportedImpl struct { + value int + } + + // Okay - exported method on unexported type (not part of public API, often used for interface satisfaction) + func (u *unexportedImpl) ExportedMethod() int { + return u.value + } + + // Okay - exported method on unexported type can return unexported types + func (u *unexportedImpl) AnotherMethod() unexported { + return unexported{} + } + + // Test for avoiding duplicate errors on embedded types with methods + + type BaseWithBadMethod struct{} + + // This method has an unexported return type - should be flagged once + func (b *BaseWithBadMethod) GetUnexported() *unexported { + ~ +!!! unexportedapi: exported API references unexported identifier unexported + return nil + } + + // This type embeds BaseWithBadMethod - should NOT re-report the GetUnexported method issue + type DerivedEmbedding struct { + BaseWithBadMethod + } + + // Test embedding unexported type with exported method that references unexported type + type unexportedBase struct{} + + // This exported method on unexported type won't be checked (unexported type methods are skipped) + func (u *unexportedBase) MethodWithBadReturn() *unexported { + return nil + } + + // This embeds an unexported type - what happens? + // OK because methods on unexported types aren't checked + type EmbeddingUnexportedBase struct { + ~ +!!! unexportedapi: exported API references unexported type unexported + unexportedBase + } + + // Test embedding unexported type with exported field that references unexported type + type unexportedBaseWithField struct { + ExportedField *unexported + } + + // Bad - embeds unexported type with exported field that references unexported type + type EmbeddingUnexportedBaseWithField struct { + ~ +!!! unexportedapi: exported API references unexported type unexported + unexportedBaseWithField + } + diff --git a/_tools/customlint/unexportedapi.go b/_tools/customlint/unexportedapi.go new file mode 100644 index 0000000000..aa5440a26d --- /dev/null +++ b/_tools/customlint/unexportedapi.go @@ -0,0 +1,389 @@ +package customlint + +import ( + "bytes" + "fmt" + "go/ast" + "go/format" + "go/types" + "slices" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" +) + +var unexportedAPIAnalyzer = &analysis.Analyzer{ + Name: "unexportedapi", + Doc: "finds exported APIs referencing unexported identifiers", + Requires: []*analysis.Analyzer{ + inspect.Analyzer, + }, + Run: func(pass *analysis.Pass) (any, error) { + return (&unexportedAPIPass{pass: pass}).run() + }, +} + +type unexportedAPIPass struct { + pass *analysis.Pass + file *ast.File + currDecl ast.Node + // Track which types/objects we've already checked to avoid duplicates + checked map[types.Object]bool +} + +func (u *unexportedAPIPass) run() (any, error) { + u.checked = make(map[types.Object]bool) + inspect := u.pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + + nodeFilter := []ast.Node{ + (*ast.File)(nil), + (*ast.FuncDecl)(nil), + (*ast.TypeSpec)(nil), + (*ast.ValueSpec)(nil), + } + + inspect.Preorder(nodeFilter, func(n ast.Node) { + u.currDecl = n + switch n := n.(type) { + case *ast.File: + u.file = n + case *ast.FuncDecl: + u.checkFuncDecl(n) + case *ast.TypeSpec: + u.checkTypeSpec(n) + case *ast.ValueSpec: + u.checkValueSpec(n) + } + }) + + return nil, nil +} + +func (u *unexportedAPIPass) checkFuncDecl(fn *ast.FuncDecl) { + if !fn.Name.IsExported() { + return + } + + // Get the method object to mark it as checked + var methodObj types.Object + if fn.Name != nil { + methodObj = u.pass.TypesInfo.Defs[fn.Name] + } + + // If this is a method on an unexported type, skip it + // Unexported types and their methods (even if exported) are not part of the public API + if fn.Recv != nil && len(fn.Recv.List) > 0 { + recvType := fn.Recv.List[0].Type + // Unwrap pointer receiver if needed + if star, ok := recvType.(*ast.StarExpr); ok { + recvType = star.X + } + // Check if the receiver type is unexported + if ident, ok := recvType.(*ast.Ident); ok && !ident.IsExported() { + return + } + } + + // Mark this method as checked so we don't check it again through embedding + if methodObj != nil { + u.checked[methodObj] = true + } + + u.checkExpr(fn.Type) +} + +func (u *unexportedAPIPass) checkTypeSpec(ts *ast.TypeSpec) { + if !ts.Name.IsExported() { + return + } + + if ts.TypeParams != nil { + for _, param := range ts.TypeParams.List { + if anyIdentExported(param.Names) { + if u.checkField(param) { + return + } + } + } + } + + u.checkExpr(ts.Type) +} + +func (u *unexportedAPIPass) checkValueSpec(vs *ast.ValueSpec) { + if !anyIdentExported(vs.Names) { + return + } + + // If there's an explicit type annotation, check it + if vs.Type != nil { + u.checkExpr(vs.Type) + return + } + + // If there's no explicit type, we need to check the inferred type, not the initialization expression + // The initialization expression is an implementation detail and not part of the API + // For example: var Foo = unexportedFunc() where unexportedFunc returns an exported type is OK + for _, name := range vs.Names { + if !name.IsExported() { + continue + } + obj := u.pass.TypesInfo.Defs[name] + if obj != nil { + if u.checkType(obj.Type()) { + return + } + } + } +} + +func anyIdentExported(idents []*ast.Ident) bool { + for _, ident := range idents { + if ident.IsExported() { + return true + } + } + return false +} + +func (u *unexportedAPIPass) checkFieldIfNamesExported(field *ast.Field) (stop bool) { + // For embedded fields (no names), handle specially + if len(field.Names) == 0 { + return u.checkEmbeddedField(field) + } + // For named fields, only check if at least one name is exported + if anyIdentExported(field.Names) { + return u.checkField(field) + } + return false +} + +func (u *unexportedAPIPass) checkEmbeddedField(field *ast.Field) (stop bool) { + if field.Type == nil { + return false + } + + // Get the type of the embedded field + typ := u.pass.TypesInfo.TypeOf(field.Type) + if typ == nil { + // Fallback to regular checking if we can't get type info + return u.checkField(field) + } + + // For embedded fields, walk through all exported members and check them. + // Use the checked map to avoid re-checking members we've already seen. + + // Dereference pointers + if ptr, ok := typ.(*types.Pointer); ok { + typ = ptr.Elem() + } + + // Check exported fields in structs + if structType, ok := typ.Underlying().(*types.Struct); ok { + for field := range structType.Fields() { + if field.Exported() && u.checkObjectType(field) { + return true + } + } + } + + // Check exported methods on the type + if named, ok := typ.(*types.Named); ok { + for method := range named.Methods() { + if method.Exported() && u.checkObjectType(method) { + return true + } + } + } + + return false +} + +// checkObjectType checks a types.Object and memoizes it to avoid duplicate checks +func (u *unexportedAPIPass) checkObjectType(obj types.Object) (stop bool) { + if obj == nil { + return false + } + + // If we've already checked this object, skip it + if u.checked[obj] { + return false + } + u.checked[obj] = true + + return u.checkType(obj.Type()) +} + +func (u *unexportedAPIPass) checkFieldsIgnoringNames(fields *ast.FieldList) (stop bool) { + if fields == nil { + return false + } + return slices.ContainsFunc(fields.List, u.checkField) +} + +func (u *unexportedAPIPass) checkField(field *ast.Field) (stop bool) { + if field.Type == nil { + return false + } + return u.checkExpr(field.Type) +} + +func (u *unexportedAPIPass) checkExpr(expr ast.Expr) (stop bool) { + if expr == nil { + return false + } + + switch expr := expr.(type) { + case *ast.StructType: + return slices.ContainsFunc(expr.Fields.List, u.checkFieldIfNamesExported) + case *ast.StarExpr: + return u.checkExpr(expr.X) + case *ast.Ident: + // First check Defs (for defining occurrences), then Uses (for referring occurrences) + obj := u.pass.TypesInfo.Defs[expr] + if obj == nil { + obj = u.pass.TypesInfo.Uses[expr] + } + if obj == nil { + return false + } + if !expr.IsExported() { + if obj.Parent() == types.Universe { + return false + } + // Only report if the unexported identifier is from the same package + if obj.Pkg() != nil && obj.Pkg() == u.pass.Pkg { + u.pass.Reportf(expr.Pos(), "exported API references unexported identifier %s", expr.Name) + return true + } + } + return u.checkType(obj.Type()) + case *ast.MapType: + return u.checkExpr(expr.Key) || u.checkExpr(expr.Value) + case *ast.ArrayType: + return u.checkExpr(expr.Len) || u.checkExpr(expr.Elt) + case *ast.SelectorExpr: + if !expr.Sel.IsExported() { + u.pass.Reportf(u.currDecl.Pos(), "exported API %s references unexported identifier %s", u.file.Name.Name, expr.Sel.Name) + return true + } + return false + case *ast.InterfaceType: + return slices.ContainsFunc(expr.Methods.List, u.checkFieldIfNamesExported) + case *ast.ChanType: + return u.checkExpr(expr.Value) + case *ast.FuncType: + return u.checkFieldsIgnoringNames(expr.TypeParams) || + u.checkFieldsIgnoringNames(expr.Params) || + u.checkFieldsIgnoringNames(expr.Results) + case *ast.Ellipsis: + return u.checkExpr(expr.Elt) + case *ast.CompositeLit: + return u.checkExpr(expr.Type) + case *ast.IndexListExpr: + return u.checkExpr(expr.X) || slices.ContainsFunc(expr.Indices, u.checkExpr) + case *ast.IndexExpr: + return u.checkExpr(expr.X) || u.checkExpr(expr.Index) + case *ast.UnaryExpr: + return u.checkExpr(expr.X) + case *ast.BinaryExpr: + return u.checkExpr(expr.X) || u.checkExpr(expr.Y) + case *ast.BasicLit: + return false + case *ast.CallExpr: + // For call expressions, check the function being called + // We don't check arguments since those are values, not types in the API + return u.checkExpr(expr.Fun) + case *ast.FuncLit: + // Function literals - check the function type + return u.checkExpr(expr.Type) + case *ast.ParenExpr: + return u.checkExpr(expr.X) + default: + var buf bytes.Buffer + _ = format.Node(&buf, u.pass.Fset, expr) + panic(fmt.Sprintf("%T, unhandled case %T: %s", u.currDecl, expr, buf.String())) + } +} + +func (u *unexportedAPIPass) checkType(typ types.Type) (stop bool) { + if typ == nil { + return false + } + + switch typ := typ.(type) { + case *types.Named: + // Check if the named type itself is unexported + obj := typ.Obj() + if obj != nil && !obj.Exported() && obj.Pkg() == u.pass.Pkg { + u.pass.Reportf(u.currDecl.Pos(), "exported API references unexported type %s", obj.Name()) + return true + } + // Check type arguments if any (for generics) + if typ.TypeArgs() != nil { + for t := range typ.TypeArgs().Types() { + if u.checkType(t) { + return true + } + } + } + return false + case *types.Pointer: + return u.checkType(typ.Elem()) + case *types.Slice: + return u.checkType(typ.Elem()) + case *types.Array: + return u.checkType(typ.Elem()) + case *types.Chan: + return u.checkType(typ.Elem()) + case *types.Map: + return u.checkType(typ.Key()) || u.checkType(typ.Elem()) + case *types.Signature: + // Check parameters + if typ.Params() != nil { + for v := range typ.Params().Variables() { + if u.checkType(v.Type()) { + return true + } + } + } + // Check results + if typ.Results() != nil { + for v := range typ.Results().Variables() { + if u.checkType(v.Type()) { + return true + } + } + } + return false + case *types.Struct: + // Check all fields + for field := range typ.Fields() { + // Only check exported fields + if field.Exported() { + if u.checkType(field.Type()) { + return true + } + } + } + return false + case *types.Interface: + // Check all methods + for method := range typ.Methods() { + // Only check exported methods + if method.Exported() { + if u.checkType(method.Type()) { + return true + } + } + } + return false + case *types.Basic, *types.TypeParam: + // Basic types and type parameters are always OK + return false + default: + // For any unhandled type, be conservative and don't report + return false + } +} diff --git a/internal/ast/ast.go b/internal/ast/ast.go index 2971ef562d..8a07b5d08a 100644 --- a/internal/ast/ast.go +++ b/internal/ast/ast.go @@ -263,10 +263,10 @@ func (n *Node) TemplateLiteralLikeData() *TemplateLiteralLikeBase { func (n *Node) KindString() string { return n.Kind.String() } func (n *Node) KindValue() int16 { return int16(n.Kind) } -type mutableNode Node +type MutableNode Node -func (n *Node) AsMutable() *mutableNode { return (*mutableNode)(n) } -func (n *mutableNode) SetModifiers(modifiers *ModifierList) { n.data.setModifiers(modifiers) } +func (n *Node) AsMutable() *MutableNode { return (*MutableNode)(n) } +func (n *MutableNode) SetModifiers(modifiers *ModifierList) { n.data.setModifiers(modifiers) } func (n *Node) Symbol() *Symbol { data := n.DeclarationData() @@ -414,7 +414,7 @@ func (n *Node) Expression() *Node { panic("Unhandled case in Node.Expression: " + n.Kind.String()) } -func (m *mutableNode) SetExpression(expr *Node) { +func (m *MutableNode) SetExpression(expr *Node) { n := (*Node)(m) switch n.Kind { case KindPropertyAccessExpression: @@ -695,7 +695,7 @@ func (n *Node) Type() *Node { return nil } -func (m *mutableNode) SetType(t *Node) { +func (m *MutableNode) SetType(t *Node) { n := (*Node)(m) switch m.Kind { case KindVariableDeclaration: @@ -787,7 +787,7 @@ func (n *Node) Initializer() *Node { panic("Unhandled case in Node.Initializer") } -func (m *mutableNode) SetInitializer(initializer *Node) { +func (m *MutableNode) SetInitializer(initializer *Node) { n := (*Node)(m) switch n.Kind { case KindVariableDeclaration: diff --git a/internal/checker/checker.go b/internal/checker/checker.go index 0ff050b0a7..17a8f4b599 100644 --- a/internal/checker/checker.go +++ b/internal/checker/checker.go @@ -846,7 +846,7 @@ type Checker struct { couldContainTypeVariables func(*Type) bool isStringIndexSignatureOnlyType func(*Type) bool markNodeAssignments func(*ast.Node) bool - emitResolver *emitResolver + emitResolver *EmitResolver emitResolverOnce sync.Once _jsxNamespace string _jsxFactoryEntity *ast.Node @@ -30908,7 +30908,7 @@ func (c *Checker) GetTypeAtLocation(node *ast.Node) *Type { return c.getTypeOfNode(node) } -func (c *Checker) GetEmitResolver() *emitResolver { +func (c *Checker) GetEmitResolver() *EmitResolver { c.emitResolverOnce.Do(func() { c.emitResolver = newEmitResolver(c) }) diff --git a/internal/checker/emitresolver.go b/internal/checker/emitresolver.go index 14d9ecd2bc..ebd3a67936 100644 --- a/internal/checker/emitresolver.go +++ b/internal/checker/emitresolver.go @@ -15,7 +15,7 @@ import ( "github.com/microsoft/typescript-go/internal/printer" ) -var _ printer.EmitResolver = (*emitResolver)(nil) +var _ printer.EmitResolver = (*EmitResolver)(nil) // Links for jsx type JSXLinks struct { @@ -32,7 +32,7 @@ type DeclarationFileLinks struct { aliasesMarked bool // if file has had alias visibility marked } -type emitResolver struct { +type EmitResolver struct { checker *Checker checkerMu sync.Mutex isValueAliasDeclaration func(node *ast.Node) bool @@ -43,32 +43,32 @@ type emitResolver struct { declarationFileLinks core.LinkStore[*ast.Node, DeclarationFileLinks] } -func newEmitResolver(checker *Checker) *emitResolver { - e := &emitResolver{checker: checker} +func newEmitResolver(checker *Checker) *EmitResolver { + e := &EmitResolver{checker: checker} e.isValueAliasDeclaration = e.isValueAliasDeclarationWorker e.aliasMarkingVisitor = e.aliasMarkingVisitorWorker return e } -func (r *emitResolver) GetJsxFactoryEntity(location *ast.Node) *ast.Node { +func (r *EmitResolver) GetJsxFactoryEntity(location *ast.Node) *ast.Node { r.checkerMu.Lock() defer r.checkerMu.Unlock() return r.checker.getJsxFactoryEntity(location) } -func (r *emitResolver) GetJsxFragmentFactoryEntity(location *ast.Node) *ast.Node { +func (r *EmitResolver) GetJsxFragmentFactoryEntity(location *ast.Node) *ast.Node { r.checkerMu.Lock() defer r.checkerMu.Unlock() return r.checker.getJsxFragmentFactoryEntity(location) } -func (r *emitResolver) IsOptionalParameter(node *ast.Node) bool { +func (r *EmitResolver) IsOptionalParameter(node *ast.Node) bool { r.checkerMu.Lock() defer r.checkerMu.Unlock() return r.isOptionalParameter(node) } -func (r *emitResolver) IsLateBound(node *ast.Node) bool { +func (r *EmitResolver) IsLateBound(node *ast.Node) bool { // TODO: Require an emitContext to construct an EmitResolver, remove all emitContext arguments // node = r.emitContext.ParseNode(node) if node == nil { @@ -86,7 +86,7 @@ func (r *emitResolver) IsLateBound(node *ast.Node) bool { return symbol.CheckFlags&ast.CheckFlagsLate != 0 } -func (r *emitResolver) GetEnumMemberValue(node *ast.Node) evaluator.Result { +func (r *EmitResolver) GetEnumMemberValue(node *ast.Node) evaluator.Result { // node = r.emitContext.ParseNode(node) if !ast.IsParseTreeNode(node) { return evaluator.NewResult(nil, false, false, false) @@ -101,14 +101,14 @@ func (r *emitResolver) GetEnumMemberValue(node *ast.Node) evaluator.Result { return r.checker.enumMemberLinks.Get(node).value } -func (r *emitResolver) IsDeclarationVisible(node *ast.Node) bool { +func (r *EmitResolver) IsDeclarationVisible(node *ast.Node) bool { // Only lock on external API func to prevent deadlocks r.checkerMu.Lock() defer r.checkerMu.Unlock() return r.isDeclarationVisible(node) } -func (r *emitResolver) isDeclarationVisible(node *ast.Node) bool { +func (r *EmitResolver) isDeclarationVisible(node *ast.Node) bool { // node = r.emitContext.ParseNode(node) if !ast.IsParseTreeNode(node) { return false @@ -128,7 +128,7 @@ func (r *emitResolver) isDeclarationVisible(node *ast.Node) bool { return links.isVisible == core.TSTrue } -func (r *emitResolver) determineIfDeclarationIsVisible(node *ast.Node) bool { +func (r *EmitResolver) determineIfDeclarationIsVisible(node *ast.Node) bool { switch node.Kind { case ast.KindJSDocCallbackTag, // ast.KindJSDocEnumTag, // !!! TODO: JSDoc @enum support? @@ -223,7 +223,7 @@ func (r *emitResolver) determineIfDeclarationIsVisible(node *ast.Node) bool { } } -func (r *emitResolver) PrecalculateDeclarationEmitVisibility(file *ast.SourceFile) { +func (r *EmitResolver) PrecalculateDeclarationEmitVisibility(file *ast.SourceFile) { r.checkerMu.Lock() defer r.checkerMu.Unlock() if r.declarationFileLinks.Get(file.AsNode()).aliasesMarked { @@ -236,7 +236,7 @@ func (r *emitResolver) PrecalculateDeclarationEmitVisibility(file *ast.SourceFil file.AsNode().ForEachChild(r.aliasMarkingVisitor) } -func (r *emitResolver) aliasMarkingVisitorWorker(node *ast.Node) bool { +func (r *EmitResolver) aliasMarkingVisitorWorker(node *ast.Node) bool { switch node.Kind { case ast.KindExportAssignment, ast.KindJSExportAssignment: if node.AsExportAssignment().Expression.Kind == ast.KindIdentifier { @@ -250,7 +250,7 @@ func (r *emitResolver) aliasMarkingVisitorWorker(node *ast.Node) bool { // Sets the isVisible link on statements the Identifier or ExportName node points at // Follows chains of import d = a.b.c -func (r *emitResolver) markLinkedAliases(node *ast.Node) { +func (r *EmitResolver) markLinkedAliases(node *ast.Node) { var exportSymbol *ast.Symbol if node.Kind != ast.KindStringLiteral && node.Parent != nil && node.Parent.Kind == ast.KindExportAssignment { exportSymbol = r.checker.resolveName(node, node.AsIdentifier().Text, ast.SymbolFlagsValue|ast.SymbolFlagsType|ast.SymbolFlagsNamespace|ast.SymbolFlagsAlias /*nameNotFoundMessage*/, nil /*isUse*/, false, false) @@ -305,13 +305,13 @@ func getMeaningOfEntityNameReference(entityName *ast.Node) ast.SymbolFlags { return ast.SymbolFlagsType } -func (r *emitResolver) IsEntityNameVisible(entityName *ast.Node, enclosingDeclaration *ast.Node) printer.SymbolAccessibilityResult { +func (r *EmitResolver) IsEntityNameVisible(entityName *ast.Node, enclosingDeclaration *ast.Node) printer.SymbolAccessibilityResult { r.checkerMu.Lock() defer r.checkerMu.Unlock() return r.isEntityNameVisible(entityName, enclosingDeclaration, true) } -func (r *emitResolver) isEntityNameVisible(entityName *ast.Node, enclosingDeclaration *ast.Node, shouldComputeAliasToMakeVisible bool) printer.SymbolAccessibilityResult { +func (r *EmitResolver) isEntityNameVisible(entityName *ast.Node, enclosingDeclaration *ast.Node, shouldComputeAliasToMakeVisible bool) printer.SymbolAccessibilityResult { // node = r.emitContext.ParseNode(entityName) if !ast.IsParseTreeNode(entityName) { return printer.SymbolAccessibilityResult{Accessibility: printer.SymbolAccessibilityNotAccessible} @@ -355,7 +355,7 @@ func (r *emitResolver) isEntityNameVisible(entityName *ast.Node, enclosingDeclar func noopAddVisibleAlias(declaration *ast.Node, aliasingStatement *ast.Node) {} -func (r *emitResolver) hasVisibleDeclarations(symbol *ast.Symbol, shouldComputeAliasToMakeVisible bool) *printer.SymbolAccessibilityResult { +func (r *EmitResolver) hasVisibleDeclarations(symbol *ast.Symbol, shouldComputeAliasToMakeVisible bool) *printer.SymbolAccessibilityResult { var aliasesToMakeVisibleSet map[ast.NodeId]*ast.Node var addVisibleAlias func(declaration *ast.Node, aliasingStatement *ast.Node) @@ -439,7 +439,7 @@ func (r *emitResolver) hasVisibleDeclarations(symbol *ast.Symbol, shouldComputeA } } -func (r *emitResolver) IsImplementationOfOverload(node *ast.SignatureDeclaration) bool { +func (r *EmitResolver) IsImplementationOfOverload(node *ast.SignatureDeclaration) bool { // node = r.emitContext.ParseNode(node) if !ast.IsParseTreeNode(node) { return false @@ -476,7 +476,7 @@ func (r *emitResolver) IsImplementationOfOverload(node *ast.SignatureDeclaration return false } -func (r *emitResolver) IsImportRequiredByAugmentation(decl *ast.ImportDeclaration) bool { +func (r *EmitResolver) IsImportRequiredByAugmentation(decl *ast.ImportDeclaration) bool { // node = r.emitContext.ParseNode(node) if !ast.IsParseTreeNode(decl.AsNode()) { return false @@ -512,7 +512,7 @@ func (r *emitResolver) IsImportRequiredByAugmentation(decl *ast.ImportDeclaratio return false } -func (r *emitResolver) IsDefinitelyReferenceToGlobalSymbolObject(node *ast.Node) bool { +func (r *EmitResolver) IsDefinitelyReferenceToGlobalSymbolObject(node *ast.Node) bool { if !ast.IsPropertyAccessExpression(node) || !ast.IsIdentifier(node.Name()) || !ast.IsPropertyAccessExpression(node.Expression()) && !ast.IsIdentifier(node.Expression()) { @@ -536,7 +536,7 @@ func (r *emitResolver) IsDefinitelyReferenceToGlobalSymbolObject(node *ast.Node) return r.checker.getResolvedSymbol(node.Expression().Expression()) == r.checker.globalThisSymbol } -func (r *emitResolver) RequiresAddingImplicitUndefined(declaration *ast.Node, symbol *ast.Symbol, enclosingDeclaration *ast.Node) bool { +func (r *EmitResolver) RequiresAddingImplicitUndefined(declaration *ast.Node, symbol *ast.Symbol, enclosingDeclaration *ast.Node) bool { if !ast.IsParseTreeNode(declaration) { return false } @@ -545,7 +545,7 @@ func (r *emitResolver) RequiresAddingImplicitUndefined(declaration *ast.Node, sy return r.requiresAddingImplicitUndefined(declaration, symbol, enclosingDeclaration) } -func (r *emitResolver) requiresAddingImplicitUndefined(declaration *ast.Node, symbol *ast.Symbol, enclosingDeclaration *ast.Node) bool { +func (r *EmitResolver) requiresAddingImplicitUndefined(declaration *ast.Node, symbol *ast.Symbol, enclosingDeclaration *ast.Node) bool { // node = r.emitContext.ParseNode(node) if !ast.IsParseTreeNode(declaration) { return false @@ -565,11 +565,11 @@ func (r *emitResolver) requiresAddingImplicitUndefined(declaration *ast.Node, sy } } -func (r *emitResolver) requiresAddingImplicitUndefinedWorker(parameter *ast.Node, enclosingDeclaration *ast.Node) bool { +func (r *EmitResolver) requiresAddingImplicitUndefinedWorker(parameter *ast.Node, enclosingDeclaration *ast.Node) bool { return (r.isRequiredInitializedParameter(parameter, enclosingDeclaration) || r.isOptionalUninitializedParameterProperty(parameter)) && !r.declaredParameterTypeContainsUndefined(parameter) } -func (r *emitResolver) declaredParameterTypeContainsUndefined(parameter *ast.Node) bool { +func (r *EmitResolver) declaredParameterTypeContainsUndefined(parameter *ast.Node) bool { // typeNode := getNonlocalEffectiveTypeAnnotationNode(parameter); // !!! JSDoc Support typeNode := parameter.Type() if typeNode == nil { @@ -582,14 +582,14 @@ func (r *emitResolver) declaredParameterTypeContainsUndefined(parameter *ast.Nod return r.checker.isErrorType(t) || r.checker.containsUndefinedType(t) } -func (r *emitResolver) isOptionalUninitializedParameterProperty(parameter *ast.Node) bool { +func (r *EmitResolver) isOptionalUninitializedParameterProperty(parameter *ast.Node) bool { return r.checker.strictNullChecks && r.isOptionalParameter(parameter) && ( /*isJSDocParameterTag(parameter) ||*/ parameter.Initializer() == nil) && // !!! TODO: JSDoc support ast.HasSyntacticModifier(parameter, ast.ModifierFlagsParameterPropertyModifier) } -func (r *emitResolver) isRequiredInitializedParameter(parameter *ast.Node, enclosingDeclaration *ast.Node) bool { +func (r *EmitResolver) isRequiredInitializedParameter(parameter *ast.Node, enclosingDeclaration *ast.Node) bool { if !r.checker.strictNullChecks || r.isOptionalParameter(parameter) || /*isJSDocParameterTag(parameter) ||*/ parameter.Initializer() == nil { // !!! TODO: JSDoc Support return false } @@ -599,7 +599,7 @@ func (r *emitResolver) isRequiredInitializedParameter(parameter *ast.Node, enclo return true } -func (r *emitResolver) isOptionalParameter(node *ast.Node) bool { +func (r *EmitResolver) isOptionalParameter(node *ast.Node) bool { // !!! TODO: JSDoc support // if (hasEffectiveQuestionToken(node)) { // return true; @@ -630,7 +630,7 @@ func (r *emitResolver) isOptionalParameter(node *ast.Node) bool { return false } -func (r *emitResolver) IsLiteralConstDeclaration(node *ast.Node) bool { +func (r *EmitResolver) IsLiteralConstDeclaration(node *ast.Node) bool { // node = r.emitContext.ParseNode(node) if !ast.IsParseTreeNode(node) { return false @@ -643,17 +643,17 @@ func (r *emitResolver) IsLiteralConstDeclaration(node *ast.Node) bool { return false } -func (r *emitResolver) IsExpandoFunctionDeclaration(node *ast.Node) bool { +func (r *EmitResolver) IsExpandoFunctionDeclaration(node *ast.Node) bool { // node = r.emitContext.ParseNode(node) // !!! TODO: expando function support return false } -func (r *emitResolver) isSymbolAccessible(symbol *ast.Symbol, enclosingDeclaration *ast.Node, meaning ast.SymbolFlags, shouldComputeAliasToMarkVisible bool) printer.SymbolAccessibilityResult { +func (r *EmitResolver) isSymbolAccessible(symbol *ast.Symbol, enclosingDeclaration *ast.Node, meaning ast.SymbolFlags, shouldComputeAliasToMarkVisible bool) printer.SymbolAccessibilityResult { return r.checker.IsSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasToMarkVisible) } -func (r *emitResolver) IsSymbolAccessible(symbol *ast.Symbol, enclosingDeclaration *ast.Node, meaning ast.SymbolFlags, shouldComputeAliasToMarkVisible bool) printer.SymbolAccessibilityResult { +func (r *EmitResolver) IsSymbolAccessible(symbol *ast.Symbol, enclosingDeclaration *ast.Node, meaning ast.SymbolFlags, shouldComputeAliasToMarkVisible bool) printer.SymbolAccessibilityResult { // TODO: Split into locking and non-locking API methods - only current usage is the symbol tracker, which is non-locking, // as all tracker calls happen within a CreateX call below, which already holds a lock // r.checkerMu.Lock() @@ -665,7 +665,7 @@ func isConstEnumOrConstEnumOnlyModule(s *ast.Symbol) bool { return isConstEnumSymbol(s) || s.Flags&ast.SymbolFlagsConstEnumOnlyModule != 0 } -func (r *emitResolver) IsReferencedAliasDeclaration(node *ast.Node) bool { +func (r *EmitResolver) IsReferencedAliasDeclaration(node *ast.Node) bool { c := r.checker if !c.canCollectSymbolAliasAccessibilityData || !ast.IsParseTreeNode(node) { return true @@ -691,7 +691,7 @@ func (r *emitResolver) IsReferencedAliasDeclaration(node *ast.Node) bool { return false } -func (r *emitResolver) IsValueAliasDeclaration(node *ast.Node) bool { +func (r *EmitResolver) IsValueAliasDeclaration(node *ast.Node) bool { c := r.checker if !c.canCollectSymbolAliasAccessibilityData || !ast.IsParseTreeNode(node) { return true @@ -703,7 +703,7 @@ func (r *emitResolver) IsValueAliasDeclaration(node *ast.Node) bool { return r.isValueAliasDeclarationWorker(node) } -func (r *emitResolver) isValueAliasDeclarationWorker(node *ast.Node) bool { +func (r *EmitResolver) isValueAliasDeclarationWorker(node *ast.Node) bool { c := r.checker switch node.Kind { @@ -728,7 +728,7 @@ func (r *emitResolver) isValueAliasDeclarationWorker(node *ast.Node) bool { return false } -func (r *emitResolver) isAliasResolvedToValue(symbol *ast.Symbol, excludeTypeOnlyValues bool) bool { +func (r *EmitResolver) isAliasResolvedToValue(symbol *ast.Symbol, excludeTypeOnlyValues bool) bool { c := r.checker if symbol == nil { return false @@ -753,7 +753,7 @@ func (r *emitResolver) isAliasResolvedToValue(symbol *ast.Symbol, excludeTypeOnl !isConstEnumOrConstEnumOnlyModule(target)) } -func (r *emitResolver) IsTopLevelValueImportEqualsWithEntityName(node *ast.Node) bool { +func (r *EmitResolver) IsTopLevelValueImportEqualsWithEntityName(node *ast.Node) bool { c := r.checker if !c.canCollectSymbolAliasAccessibilityData { return true @@ -772,7 +772,7 @@ func (r *emitResolver) IsTopLevelValueImportEqualsWithEntityName(node *ast.Node) return r.isAliasResolvedToValue(c.getSymbolOfDeclaration(node), false /*excludeTypeOnlyValues*/) } -func (r *emitResolver) MarkLinkedReferencesRecursively(file *ast.SourceFile) { +func (r *EmitResolver) MarkLinkedReferencesRecursively(file *ast.SourceFile) { r.checkerMu.Lock() defer r.checkerMu.Unlock() @@ -796,7 +796,7 @@ func (r *emitResolver) MarkLinkedReferencesRecursively(file *ast.SourceFile) { } } -func (r *emitResolver) GetExternalModuleFileFromDeclaration(declaration *ast.Node) *ast.SourceFile { +func (r *EmitResolver) GetExternalModuleFileFromDeclaration(declaration *ast.Node) *ast.SourceFile { if !ast.IsParseTreeNode(declaration) { return nil } @@ -822,7 +822,7 @@ func (r *emitResolver) GetExternalModuleFileFromDeclaration(declaration *ast.Nod return decl.AsSourceFile() } -func (r *emitResolver) getReferenceResolver() binder.ReferenceResolver { +func (r *EmitResolver) getReferenceResolver() binder.ReferenceResolver { if r.referenceResolver == nil { r.referenceResolver = binder.NewReferenceResolver(r.checker.compilerOptions, binder.ReferenceResolverHooks{ ResolveName: r.checker.resolveName, @@ -838,7 +838,7 @@ func (r *emitResolver) getReferenceResolver() binder.ReferenceResolver { return r.referenceResolver } -func (r *emitResolver) GetReferencedExportContainer(node *ast.IdentifierNode, prefixLocals bool) *ast.Node /*SourceFile|ModuleDeclaration|EnumDeclaration*/ { +func (r *EmitResolver) GetReferencedExportContainer(node *ast.IdentifierNode, prefixLocals bool) *ast.Node /*SourceFile|ModuleDeclaration|EnumDeclaration*/ { if !ast.IsParseTreeNode(node) { return nil } @@ -849,13 +849,13 @@ func (r *emitResolver) GetReferencedExportContainer(node *ast.IdentifierNode, pr return r.getReferenceResolver().GetReferencedExportContainer(node, prefixLocals) } -func (r *emitResolver) SetReferencedImportDeclaration(node *ast.IdentifierNode, ref *ast.Declaration) { +func (r *EmitResolver) SetReferencedImportDeclaration(node *ast.IdentifierNode, ref *ast.Declaration) { r.checkerMu.Lock() defer r.checkerMu.Unlock() r.jsxLinks.Get(node).importRef = ref } -func (r *emitResolver) GetReferencedImportDeclaration(node *ast.IdentifierNode) *ast.Declaration { +func (r *EmitResolver) GetReferencedImportDeclaration(node *ast.IdentifierNode) *ast.Declaration { r.checkerMu.Lock() defer r.checkerMu.Unlock() if !ast.IsParseTreeNode(node) { @@ -865,7 +865,7 @@ func (r *emitResolver) GetReferencedImportDeclaration(node *ast.IdentifierNode) return r.getReferenceResolver().GetReferencedImportDeclaration(node) } -func (r *emitResolver) GetReferencedValueDeclaration(node *ast.IdentifierNode) *ast.Declaration { +func (r *EmitResolver) GetReferencedValueDeclaration(node *ast.IdentifierNode) *ast.Declaration { if !ast.IsParseTreeNode(node) { return nil } @@ -876,7 +876,7 @@ func (r *emitResolver) GetReferencedValueDeclaration(node *ast.IdentifierNode) * return r.getReferenceResolver().GetReferencedValueDeclaration(node) } -func (r *emitResolver) GetReferencedValueDeclarations(node *ast.IdentifierNode) []*ast.Declaration { +func (r *EmitResolver) GetReferencedValueDeclarations(node *ast.IdentifierNode) []*ast.Declaration { if !ast.IsParseTreeNode(node) { return nil } @@ -887,7 +887,7 @@ func (r *emitResolver) GetReferencedValueDeclarations(node *ast.IdentifierNode) return r.getReferenceResolver().GetReferencedValueDeclarations(node) } -func (r *emitResolver) GetElementAccessExpressionName(expression *ast.ElementAccessExpression) string { +func (r *EmitResolver) GetElementAccessExpressionName(expression *ast.ElementAccessExpression) string { if !ast.IsParseTreeNode(expression.AsNode()) { return "" } @@ -902,7 +902,7 @@ func (r *emitResolver) GetElementAccessExpressionName(expression *ast.ElementAcc // and requires giving it access to a lot of context it's otherwise not required to have, which also further complicates the API // and likely reduces performance. There's probably some refactoring that could be done here to simplify this. -func (r *emitResolver) CreateReturnTypeOfSignatureDeclaration(emitContext *printer.EmitContext, signatureDeclaration *ast.Node, enclosingDeclaration *ast.Node, flags nodebuilder.Flags, internalFlags nodebuilder.InternalFlags, tracker nodebuilder.SymbolTracker) *ast.Node { +func (r *EmitResolver) CreateReturnTypeOfSignatureDeclaration(emitContext *printer.EmitContext, signatureDeclaration *ast.Node, enclosingDeclaration *ast.Node, flags nodebuilder.Flags, internalFlags nodebuilder.InternalFlags, tracker nodebuilder.SymbolTracker) *ast.Node { original := emitContext.ParseNode(signatureDeclaration) if original == nil { return emitContext.Factory.NewKeywordTypeNode(ast.KindAnyKeyword) @@ -914,7 +914,7 @@ func (r *emitResolver) CreateReturnTypeOfSignatureDeclaration(emitContext *print return requestNodeBuilder.SerializeReturnTypeForSignature(original, enclosingDeclaration, flags, internalFlags, tracker) } -func (r *emitResolver) CreateTypeParametersOfSignatureDeclaration(emitContext *printer.EmitContext, signatureDeclaration *ast.Node, enclosingDeclaration *ast.Node, flags nodebuilder.Flags, internalFlags nodebuilder.InternalFlags, tracker nodebuilder.SymbolTracker) []*ast.Node { +func (r *EmitResolver) CreateTypeParametersOfSignatureDeclaration(emitContext *printer.EmitContext, signatureDeclaration *ast.Node, enclosingDeclaration *ast.Node, flags nodebuilder.Flags, internalFlags nodebuilder.InternalFlags, tracker nodebuilder.SymbolTracker) []*ast.Node { original := emitContext.ParseNode(signatureDeclaration) if original == nil { return nil @@ -926,7 +926,7 @@ func (r *emitResolver) CreateTypeParametersOfSignatureDeclaration(emitContext *p return requestNodeBuilder.SerializeTypeParametersForSignature(original, enclosingDeclaration, flags, internalFlags, tracker) } -func (r *emitResolver) CreateTypeOfDeclaration(emitContext *printer.EmitContext, declaration *ast.Node, enclosingDeclaration *ast.Node, flags nodebuilder.Flags, internalFlags nodebuilder.InternalFlags, tracker nodebuilder.SymbolTracker) *ast.Node { +func (r *EmitResolver) CreateTypeOfDeclaration(emitContext *printer.EmitContext, declaration *ast.Node, enclosingDeclaration *ast.Node, flags nodebuilder.Flags, internalFlags nodebuilder.InternalFlags, tracker nodebuilder.SymbolTracker) *ast.Node { original := emitContext.ParseNode(declaration) if original == nil { return emitContext.Factory.NewKeywordTypeNode(ast.KindAnyKeyword) @@ -940,7 +940,7 @@ func (r *emitResolver) CreateTypeOfDeclaration(emitContext *printer.EmitContext, return requestNodeBuilder.SerializeTypeForDeclaration(declaration, symbol, enclosingDeclaration, flags|nodebuilder.FlagsMultilineObjectLiterals, internalFlags, tracker) } -func (r *emitResolver) CreateLiteralConstValue(emitContext *printer.EmitContext, node *ast.Node, tracker nodebuilder.SymbolTracker) *ast.Node { +func (r *EmitResolver) CreateLiteralConstValue(emitContext *printer.EmitContext, node *ast.Node, tracker nodebuilder.SymbolTracker) *ast.Node { node = emitContext.ParseNode(node) r.checkerMu.Lock() t := r.checker.getTypeOfSymbol(r.checker.getSymbolOfDeclaration(node)) @@ -992,7 +992,7 @@ func (r *emitResolver) CreateLiteralConstValue(emitContext *printer.EmitContext, panic("unhandled literal const value kind") } -func (r *emitResolver) CreateTypeOfExpression(emitContext *printer.EmitContext, expression *ast.Node, enclosingDeclaration *ast.Node, flags nodebuilder.Flags, internalFlags nodebuilder.InternalFlags, tracker nodebuilder.SymbolTracker) *ast.Node { +func (r *EmitResolver) CreateTypeOfExpression(emitContext *printer.EmitContext, expression *ast.Node, enclosingDeclaration *ast.Node, flags nodebuilder.Flags, internalFlags nodebuilder.InternalFlags, tracker nodebuilder.SymbolTracker) *ast.Node { expression = emitContext.ParseNode(expression) if expression == nil { return emitContext.Factory.NewKeywordTypeNode(ast.KindAnyKeyword) @@ -1004,7 +1004,7 @@ func (r *emitResolver) CreateTypeOfExpression(emitContext *printer.EmitContext, return requestNodeBuilder.SerializeTypeForExpression(expression, enclosingDeclaration, flags|nodebuilder.FlagsMultilineObjectLiterals, internalFlags, tracker) } -func (r *emitResolver) CreateLateBoundIndexSignatures(emitContext *printer.EmitContext, container *ast.Node, enclosingDeclaration *ast.Node, flags nodebuilder.Flags, internalFlags nodebuilder.InternalFlags, tracker nodebuilder.SymbolTracker) []*ast.Node { +func (r *EmitResolver) CreateLateBoundIndexSignatures(emitContext *printer.EmitContext, container *ast.Node, enclosingDeclaration *ast.Node, flags nodebuilder.Flags, internalFlags nodebuilder.InternalFlags, tracker nodebuilder.SymbolTracker) []*ast.Node { container = emitContext.ParseNode(container) r.checkerMu.Lock() defer r.checkerMu.Unlock() @@ -1097,21 +1097,21 @@ func (r *emitResolver) CreateLateBoundIndexSignatures(emitContext *printer.EmitC return result } -func (r *emitResolver) GetEffectiveDeclarationFlags(node *ast.Node, flags ast.ModifierFlags) ast.ModifierFlags { +func (r *EmitResolver) GetEffectiveDeclarationFlags(node *ast.Node, flags ast.ModifierFlags) ast.ModifierFlags { // node = emitContext.ParseNode(node) r.checkerMu.Lock() defer r.checkerMu.Unlock() return r.checker.GetEffectiveDeclarationFlags(node, flags) } -func (r *emitResolver) GetResolutionModeOverride(node *ast.Node) core.ResolutionMode { +func (r *EmitResolver) GetResolutionModeOverride(node *ast.Node) core.ResolutionMode { // node = emitContext.ParseNode(node) r.checkerMu.Lock() defer r.checkerMu.Unlock() return r.checker.GetResolutionModeOverride(node.AsImportAttributes(), false) } -func (r *emitResolver) GetConstantValue(node *ast.Node) any { +func (r *EmitResolver) GetConstantValue(node *ast.Node) any { // node = emitContext.ParseNode(node) r.checkerMu.Lock() defer r.checkerMu.Unlock() diff --git a/internal/checker/nodebuilder.go b/internal/checker/nodebuilder.go index bd629596c7..484c5abfc5 100644 --- a/internal/checker/nodebuilder.go +++ b/internal/checker/nodebuilder.go @@ -9,7 +9,7 @@ import ( type NodeBuilder struct { ctxStack []*NodeBuilderContext basicHost Host - impl *nodeBuilderImpl + impl *NodeBuilderImpl } // EmitContext implements NodeBuilderInterface. diff --git a/internal/checker/nodebuilderimpl.go b/internal/checker/nodebuilderimpl.go index 5ac9b95369..be7e354b72 100644 --- a/internal/checker/nodebuilderimpl.go +++ b/internal/checker/nodebuilderimpl.go @@ -83,7 +83,7 @@ type NodeBuilderContext struct { typeParameterSymbolList map[ast.SymbolId]struct{} } -type nodeBuilderImpl struct { +type NodeBuilderImpl struct { // host members f *ast.NodeFactory ch *Checker @@ -107,13 +107,13 @@ const ( // Node builder utility functions -func newNodeBuilderImpl(ch *Checker, e *printer.EmitContext) *nodeBuilderImpl { - b := &nodeBuilderImpl{f: e.Factory.AsNodeFactory(), ch: ch, e: e} +func newNodeBuilderImpl(ch *Checker, e *printer.EmitContext) *NodeBuilderImpl { + b := &NodeBuilderImpl{f: e.Factory.AsNodeFactory(), ch: ch, e: e} b.cloneBindingNameVisitor = ast.NewNodeVisitor(b.cloneBindingName, b.f, ast.NodeVisitorHooks{}) return b } -func (b *nodeBuilderImpl) saveRestoreFlags() func() { +func (b *NodeBuilderImpl) saveRestoreFlags() func() { flags := b.ctx.flags internalFlags := b.ctx.internalFlags depth := b.ctx.depth @@ -125,7 +125,7 @@ func (b *nodeBuilderImpl) saveRestoreFlags() func() { } } -func (b *nodeBuilderImpl) checkTruncationLength() bool { +func (b *NodeBuilderImpl) checkTruncationLength() bool { if b.ctx.truncating { return b.ctx.truncating } @@ -133,7 +133,7 @@ func (b *nodeBuilderImpl) checkTruncationLength() bool { return b.ctx.truncating } -func (b *nodeBuilderImpl) appendReferenceToType(root *ast.TypeNode, ref *ast.TypeNode) *ast.TypeNode { +func (b *NodeBuilderImpl) appendReferenceToType(root *ast.TypeNode, ref *ast.TypeNode) *ast.TypeNode { if ast.IsImportTypeNode(root) { // first shift type arguments @@ -205,7 +205,7 @@ func isClassInstanceSide(c *Checker, t *Type) bool { return t.symbol != nil && t.symbol.Flags&ast.SymbolFlagsClass != 0 && (t == c.getDeclaredTypeOfClassOrInterface(t.symbol) || (t.flags&TypeFlagsObject != 0 && t.objectFlags&ObjectFlagsIsClassInstanceClone != 0)) } -func (b *nodeBuilderImpl) createElidedInformationPlaceholder() *ast.TypeNode { +func (b *NodeBuilderImpl) createElidedInformationPlaceholder() *ast.TypeNode { b.ctx.approximateLength += 3 if b.ctx.flags&nodebuilder.FlagsNoTruncation == 0 { return b.f.NewTypeReferenceNode(b.f.NewIdentifier("..."), nil /*typeArguments*/) @@ -213,7 +213,7 @@ func (b *nodeBuilderImpl) createElidedInformationPlaceholder() *ast.TypeNode { return b.e.AddSyntheticLeadingComment(b.f.NewKeywordTypeNode(ast.KindAnyKeyword), ast.KindMultiLineCommentTrivia, "elided", false /*hasTrailingNewLine*/) } -func (b *nodeBuilderImpl) mapToTypeNodes(list []*Type, isBareList bool) *ast.NodeList { +func (b *NodeBuilderImpl) mapToTypeNodes(list []*Type, isBareList bool) *ast.NodeList { if len(list) == 0 { return nil } @@ -327,18 +327,18 @@ func typesAreSameReference(a, b *Type) bool { return a == b || a.symbol != nil && a.symbol == b.symbol || a.alias != nil && a.alias == b.alias } -func (b *nodeBuilderImpl) setCommentRange(node *ast.Node, range_ *ast.Node) { +func (b *NodeBuilderImpl) setCommentRange(node *ast.Node, range_ *ast.Node) { if range_ != nil && b.ctx.enclosingFile != nil && b.ctx.enclosingFile == ast.GetSourceFileOfNode(range_) { // Copy comments to node for declaration emit b.e.AssignCommentRange(node, range_) } } -func (b *nodeBuilderImpl) tryReuseExistingTypeNodeHelper(existing *ast.TypeNode) *ast.TypeNode { +func (b *NodeBuilderImpl) tryReuseExistingTypeNodeHelper(existing *ast.TypeNode) *ast.TypeNode { return nil // !!! } -func (b *nodeBuilderImpl) tryReuseExistingTypeNode(typeNode *ast.TypeNode, t *Type, host *ast.Node, addUndefined bool) *ast.TypeNode { +func (b *NodeBuilderImpl) tryReuseExistingTypeNode(typeNode *ast.TypeNode, t *Type, host *ast.Node, addUndefined bool) *ast.TypeNode { originalType := t if addUndefined { t = b.ch.getOptionalType(t, !ast.IsParameter(host)) @@ -362,7 +362,7 @@ func (b *nodeBuilderImpl) tryReuseExistingTypeNode(typeNode *ast.TypeNode, t *Ty return nil } -func (b *nodeBuilderImpl) typeNodeIsEquivalentToType(annotatedDeclaration *ast.Node, t *Type, typeFromTypeNode *Type) bool { +func (b *NodeBuilderImpl) typeNodeIsEquivalentToType(annotatedDeclaration *ast.Node, t *Type, typeFromTypeNode *Type) bool { if typeFromTypeNode == t { return true } @@ -377,7 +377,7 @@ func (b *nodeBuilderImpl) typeNodeIsEquivalentToType(annotatedDeclaration *ast.N return false } -func (b *nodeBuilderImpl) existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing *ast.TypeNode, t *Type) bool { +func (b *NodeBuilderImpl) existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing *ast.TypeNode, t *Type) bool { // In JS, you can say something like `Foo` and get a `Foo` implicitly - we don't want to preserve that original `Foo` in these cases, though. if t.objectFlags&ObjectFlagsReference == 0 { return true @@ -404,7 +404,7 @@ func (b *nodeBuilderImpl) existingTypeNodeIsNotReferenceOrIsReferenceWithCompati return len(existing.TypeArguments()) >= b.ch.getMinTypeArgumentCount(t.AsTypeReference().target.AsInterfaceType().TypeParameters()) } -func (b *nodeBuilderImpl) tryReuseExistingNonParameterTypeNode(existing *ast.TypeNode, t *Type, host *ast.Node, annotationType *Type) *ast.TypeNode { +func (b *NodeBuilderImpl) tryReuseExistingNonParameterTypeNode(existing *ast.TypeNode, t *Type, host *ast.Node, annotationType *Type) *ast.TypeNode { if host == nil { host = b.ctx.enclosingDeclaration } @@ -420,7 +420,7 @@ func (b *nodeBuilderImpl) tryReuseExistingNonParameterTypeNode(existing *ast.Typ return nil } -func (b *nodeBuilderImpl) getResolvedTypeWithoutAbstractConstructSignatures(t *StructuredType) *Type { +func (b *NodeBuilderImpl) getResolvedTypeWithoutAbstractConstructSignatures(t *StructuredType) *Type { if len(t.ConstructSignatures()) == 0 { return t.AsType() } @@ -440,7 +440,7 @@ func (b *nodeBuilderImpl) getResolvedTypeWithoutAbstractConstructSignatures(t *S return typeCopy } -func (b *nodeBuilderImpl) symbolToNode(symbol *ast.Symbol, meaning ast.SymbolFlags) *ast.Node { +func (b *NodeBuilderImpl) symbolToNode(symbol *ast.Symbol, meaning ast.SymbolFlags) *ast.Node { if b.ctx.internalFlags&nodebuilder.InternalFlagsWriteComputedProps != 0 { if symbol.ValueDeclaration != nil { name := ast.GetNameOfDeclaration(symbol.ValueDeclaration) @@ -462,7 +462,7 @@ func (b *nodeBuilderImpl) symbolToNode(symbol *ast.Symbol, meaning ast.SymbolFla return b.symbolToExpression(symbol, meaning) } -func (b *nodeBuilderImpl) symbolToName(symbol *ast.Symbol, meaning ast.SymbolFlags, expectsIdentifier bool) *ast.Node { +func (b *NodeBuilderImpl) symbolToName(symbol *ast.Symbol, meaning ast.SymbolFlags, expectsIdentifier bool) *ast.Node { chain := b.lookupSymbolChain(symbol, meaning, false) if expectsIdentifier && len(chain) != 1 && !b.ctx.encounteredError && (b.ctx.flags&nodebuilder.FlagsAllowQualifiedNameInPlaceOfIdentifier != 0) { b.ctx.encounteredError = true @@ -470,7 +470,7 @@ func (b *nodeBuilderImpl) symbolToName(symbol *ast.Symbol, meaning ast.SymbolFla return b.createEntityNameFromSymbolChain(chain, len(chain)-1) } -func (b *nodeBuilderImpl) createEntityNameFromSymbolChain(chain []*ast.Symbol, index int) *ast.Node { +func (b *NodeBuilderImpl) createEntityNameFromSymbolChain(chain []*ast.Symbol, index int) *ast.Node { // typeParameterNodes := b.lookupTypeParameterNodes(chain, index) symbol := chain[index] @@ -498,7 +498,7 @@ func (b *nodeBuilderImpl) createEntityNameFromSymbolChain(chain []*ast.Symbol, i } // TODO: Audit usages of symbolToEntityNameNode - they should probably all be symbolToName -func (b *nodeBuilderImpl) symbolToEntityNameNode(symbol *ast.Symbol) *ast.EntityName { +func (b *NodeBuilderImpl) symbolToEntityNameNode(symbol *ast.Symbol) *ast.EntityName { identifier := b.f.NewIdentifier(symbol.Name) if symbol.Parent != nil { return b.f.NewQualifiedName(b.symbolToEntityNameNode(symbol.Parent), identifier) @@ -506,7 +506,7 @@ func (b *nodeBuilderImpl) symbolToEntityNameNode(symbol *ast.Symbol) *ast.Entity return identifier } -func (b *nodeBuilderImpl) symbolToTypeNode(symbol *ast.Symbol, mask ast.SymbolFlags, typeArguments *ast.NodeList) *ast.TypeNode { +func (b *NodeBuilderImpl) symbolToTypeNode(symbol *ast.Symbol, mask ast.SymbolFlags, typeArguments *ast.NodeList) *ast.TypeNode { chain := b.lookupSymbolChain(symbol, mask, (b.ctx.flags&nodebuilder.FlagsUseAliasDefinedOutsideCurrentScope == 0)) // If we're using aliases outside the current scope, dont bother with the module if len(chain) == 0 { return nil // TODO: shouldn't be possible, `lookupSymbolChain` should always at least return the input symbol and issue an error @@ -617,7 +617,7 @@ func getTopmostIndexedAccessType(node *ast.IndexedAccessTypeNode) *ast.IndexedAc return node } -func (b *nodeBuilderImpl) createAccessFromSymbolChain(chain []*ast.Symbol, index int, stopper int, overrideTypeArguments *ast.NodeList) *ast.Node { +func (b *NodeBuilderImpl) createAccessFromSymbolChain(chain []*ast.Symbol, index int, stopper int, overrideTypeArguments *ast.NodeList) *ast.Node { // !!! TODO: smuggle type arguments out typeParameterNodes := overrideTypeArguments if index != (len(chain) - 1) { @@ -718,12 +718,12 @@ func (b *nodeBuilderImpl) createAccessFromSymbolChain(chain []*ast.Symbol, index return identifier } -func (b *nodeBuilderImpl) symbolToExpression(symbol *ast.Symbol, mask ast.SymbolFlags) *ast.Expression { +func (b *NodeBuilderImpl) symbolToExpression(symbol *ast.Symbol, mask ast.SymbolFlags) *ast.Expression { chain := b.lookupSymbolChain(symbol, mask, false) return b.createExpressionFromSymbolChain(chain, len(chain)-1) } -func (b *nodeBuilderImpl) createExpressionFromSymbolChain(chain []*ast.Symbol, index int) *ast.Expression { +func (b *NodeBuilderImpl) createExpressionFromSymbolChain(chain []*ast.Symbol, index int) *ast.Expression { // typeParameterNodes := b.lookupTypeParameterNodes(chain, index) symbol := chain[index] @@ -798,7 +798,7 @@ func isDefaultBindingContext(location *ast.Node) bool { return location.Kind == ast.KindSourceFile || ast.IsAmbientModule(location) } -func (b *nodeBuilderImpl) getNameOfSymbolFromNameType(symbol *ast.Symbol) string { +func (b *NodeBuilderImpl) getNameOfSymbolFromNameType(symbol *ast.Symbol) string { if b.ch.valueSymbolLinks.Has(symbol) { nameType := b.ch.valueSymbolLinks.Get(symbol).nameType if nameType == nil { @@ -835,7 +835,7 @@ func (b *nodeBuilderImpl) getNameOfSymbolFromNameType(symbol *ast.Symbol) string * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal. * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. */ -func (b *nodeBuilderImpl) getNameOfSymbolAsWritten(symbol *ast.Symbol) string { +func (b *NodeBuilderImpl) getNameOfSymbolAsWritten(symbol *ast.Symbol) string { result, ok := b.ctx.remappedSymbolReferences[ast.GetSymbolId(symbol)] if ok { symbol = result @@ -891,14 +891,14 @@ func (b *nodeBuilderImpl) getNameOfSymbolAsWritten(symbol *ast.Symbol) string { // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus // its locally declared type parameters. -func (b *nodeBuilderImpl) getTypeParametersOfClassOrInterface(symbol *ast.Symbol) []*Type { +func (b *NodeBuilderImpl) getTypeParametersOfClassOrInterface(symbol *ast.Symbol) []*Type { result := make([]*Type, 0) result = append(result, b.ch.getOuterTypeParametersOfClassOrInterface(symbol)...) result = append(result, b.ch.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)...) return result } -func (b *nodeBuilderImpl) lookupTypeParameterNodes(chain []*ast.Symbol, index int) *ast.TypeParameterList { +func (b *NodeBuilderImpl) lookupTypeParameterNodes(chain []*ast.Symbol, index int) *ast.TypeParameterList { debug.Assert(chain != nil && 0 <= index && index < len(chain)) symbol := chain[index] symbolId := ast.GetSymbolId(symbol) @@ -940,12 +940,12 @@ func (b *nodeBuilderImpl) lookupTypeParameterNodes(chain []*ast.Symbol, index in } // TODO: move `lookupSymbolChain` and co to `symbolaccessibility.go` (but getSpecifierForModuleSymbol uses much context which makes that hard?) -func (b *nodeBuilderImpl) lookupSymbolChain(symbol *ast.Symbol, meaning ast.SymbolFlags, yieldModuleSymbol bool) []*ast.Symbol { +func (b *NodeBuilderImpl) lookupSymbolChain(symbol *ast.Symbol, meaning ast.SymbolFlags, yieldModuleSymbol bool) []*ast.Symbol { b.ctx.tracker.TrackSymbol(symbol, b.ctx.enclosingDeclaration, meaning) return b.lookupSymbolChainWorker(symbol, meaning, yieldModuleSymbol) } -func (b *nodeBuilderImpl) lookupSymbolChainWorker(symbol *ast.Symbol, meaning ast.SymbolFlags, yieldModuleSymbol bool) []*ast.Symbol { +func (b *NodeBuilderImpl) lookupSymbolChainWorker(symbol *ast.Symbol, meaning ast.SymbolFlags, yieldModuleSymbol bool) []*ast.Symbol { // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain []*ast.Symbol isTypeParameter := symbol.Flags&ast.SymbolFlagsTypeParameter != 0 @@ -966,7 +966,7 @@ type sortedSymbolNamePair struct { } /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ -func (b *nodeBuilderImpl) getSymbolChain(symbol *ast.Symbol, meaning ast.SymbolFlags, endOfChain bool, yieldModuleSymbol bool) []*ast.Symbol { +func (b *NodeBuilderImpl) getSymbolChain(symbol *ast.Symbol, meaning ast.SymbolFlags, endOfChain bool, yieldModuleSymbol bool) []*ast.Symbol { accessibleSymbolChain := b.ch.getAccessibleSymbolChain(symbol, b.ctx.enclosingDeclaration, meaning, b.ctx.flags&nodebuilder.FlagsUseOnlyExternalAliasing != 0) qualifierMeaning := meaning if len(accessibleSymbolChain) > 1 { @@ -1032,7 +1032,7 @@ func (b *nodeBuilderImpl) getSymbolChain(symbol *ast.Symbol, meaning ast.SymbolF return nil } -func (b_ *nodeBuilderImpl) sortByBestName(a sortedSymbolNamePair, b sortedSymbolNamePair) int { +func (b_ *NodeBuilderImpl) sortByBestName(a sortedSymbolNamePair, b sortedSymbolNamePair) int { specifierA := a.name specifierB := b.name if len(specifierA) > 0 && len(specifierB) > 0 { @@ -1136,7 +1136,7 @@ func tryGetModuleSpecifierFromDeclarationWorker(node *ast.Node) *ast.Node { } } -func (b *nodeBuilderImpl) getSpecifierForModuleSymbol(symbol *ast.Symbol, overrideImportMode core.ResolutionMode) string { +func (b *NodeBuilderImpl) getSpecifierForModuleSymbol(symbol *ast.Symbol, overrideImportMode core.ResolutionMode) string { file := ast.GetDeclarationOfKind(symbol, ast.KindSourceFile) if file == nil { equivalentSymbol := core.FirstNonNil(symbol.Declarations, func(d *ast.Node) *ast.Symbol { @@ -1220,7 +1220,7 @@ func (b *nodeBuilderImpl) getSpecifierForModuleSymbol(symbol *ast.Symbol, overri return specifier } -func (b *nodeBuilderImpl) typeParameterToDeclarationWithConstraint(typeParameter *Type, constraintNode *ast.TypeNode) *ast.TypeParameterDeclarationNode { +func (b *NodeBuilderImpl) typeParameterToDeclarationWithConstraint(typeParameter *Type, constraintNode *ast.TypeNode) *ast.TypeParameterDeclarationNode { restoreFlags := b.saveRestoreFlags() b.ctx.flags &= ^nodebuilder.FlagsWriteTypeParametersInQualifiedName // Avoids potential infinite loop when building for a claimspace with a generic modifiers := ast.CreateModifiersFromModifierFlags(b.ch.getTypeParameterModifiers(typeParameter), b.f.NewModifier) @@ -1252,7 +1252,7 @@ func (b *nodeBuilderImpl) typeParameterToDeclarationWithConstraint(typeParameter * * It also calls `setOriginalNode` to setup a `.original` pointer, since you basically *always* want these in the node builder. */ -func (b *nodeBuilderImpl) setTextRange(range_ *ast.Node, location *ast.Node) *ast.Node { +func (b *NodeBuilderImpl) setTextRange(range_ *ast.Node, location *ast.Node) *ast.Node { if range_ == nil { return range_ } @@ -1279,7 +1279,7 @@ func (b *nodeBuilderImpl) setTextRange(range_ *ast.Node, location *ast.Node) *as return range_ } -func (b *nodeBuilderImpl) typeParameterShadowsOtherTypeParameterInScope(name string, typeParameter *Type) bool { +func (b *NodeBuilderImpl) typeParameterShadowsOtherTypeParameterInScope(name string, typeParameter *Type) bool { result := b.ch.resolveName(b.ctx.enclosingDeclaration, name, ast.SymbolFlagsType, nil, false, false) if result != nil && result.Flags&ast.SymbolFlagsTypeParameter != 0 { return result != typeParameter.symbol @@ -1287,7 +1287,7 @@ func (b *nodeBuilderImpl) typeParameterShadowsOtherTypeParameterInScope(name str return false } -func (b *nodeBuilderImpl) typeParameterToName(typeParameter *Type) *ast.Identifier { +func (b *NodeBuilderImpl) typeParameterToName(typeParameter *Type) *ast.Identifier { if b.ctx.flags&nodebuilder.FlagsGenerateNamesForShadowedTypeParams != 0 && b.ctx.typeParameterNames != nil { cached, ok := b.ctx.typeParameterNames[typeParameter.id] if ok { @@ -1346,15 +1346,15 @@ func (b *nodeBuilderImpl) typeParameterToName(typeParameter *Type) *ast.Identifi return result.AsIdentifier() } -func (b *nodeBuilderImpl) isMappedTypeHomomorphic(mapped *Type) bool { +func (b *NodeBuilderImpl) isMappedTypeHomomorphic(mapped *Type) bool { return b.ch.getHomomorphicTypeVariable(mapped) != nil } -func (b *nodeBuilderImpl) isHomomorphicMappedTypeWithNonHomomorphicInstantiation(mapped *MappedType) bool { +func (b *NodeBuilderImpl) isHomomorphicMappedTypeWithNonHomomorphicInstantiation(mapped *MappedType) bool { return mapped.target != nil && !b.isMappedTypeHomomorphic(mapped.AsType()) && b.isMappedTypeHomomorphic(mapped.target) } -func (b *nodeBuilderImpl) createMappedTypeNodeFromType(t *Type) *ast.TypeNode { +func (b *NodeBuilderImpl) createMappedTypeNodeFromType(t *Type) *ast.TypeNode { debug.Assert(t.Flags()&TypeFlagsObject != 0) mapped := t.AsMappedType() var readonlyToken *ast.Node @@ -1470,7 +1470,7 @@ func (b *nodeBuilderImpl) createMappedTypeNodeFromType(t *Type) *ast.TypeNode { return result } -func (b *nodeBuilderImpl) typePredicateToTypePredicateNode(predicate *TypePredicate) *ast.Node { +func (b *NodeBuilderImpl) typePredicateToTypePredicateNode(predicate *TypePredicate) *ast.Node { var assertsModifier *ast.Node if predicate.kind == TypePredicateKindAssertsIdentifier || predicate.kind == TypePredicateKindAssertsThis { assertsModifier = b.f.NewToken(ast.KindAssertsKeyword) @@ -1493,7 +1493,7 @@ func (b *nodeBuilderImpl) typePredicateToTypePredicateNode(predicate *TypePredic ) } -func (b *nodeBuilderImpl) typeToTypeNodeHelperWithPossibleReusableTypeNode(t *Type, typeNode *ast.TypeNode) *ast.TypeNode { +func (b *NodeBuilderImpl) typeToTypeNodeHelperWithPossibleReusableTypeNode(t *Type, typeNode *ast.TypeNode) *ast.TypeNode { if t == nil { return b.f.NewKeywordTypeNode(ast.KindAnyKeyword) } @@ -1506,7 +1506,7 @@ func (b *nodeBuilderImpl) typeToTypeNodeHelperWithPossibleReusableTypeNode(t *Ty return b.typeToTypeNode(t) } -func (b *nodeBuilderImpl) typeParameterToDeclaration(parameter *Type) *ast.Node { +func (b *NodeBuilderImpl) typeParameterToDeclaration(parameter *Type) *ast.Node { constraint := b.ch.getConstraintOfTypeParameter(parameter) var constraintNode *ast.Node if constraint != nil { @@ -1515,11 +1515,11 @@ func (b *nodeBuilderImpl) typeParameterToDeclaration(parameter *Type) *ast.Node return b.typeParameterToDeclarationWithConstraint(parameter, constraintNode) } -func (b *nodeBuilderImpl) symbolToTypeParameterDeclarations(symbol *ast.Symbol) []*ast.Node { +func (b *NodeBuilderImpl) symbolToTypeParameterDeclarations(symbol *ast.Symbol) []*ast.Node { return b.typeParametersToTypeParameterDeclarations(symbol) } -func (b *nodeBuilderImpl) typeParametersToTypeParameterDeclarations(symbol *ast.Symbol) []*ast.Node { +func (b *NodeBuilderImpl) typeParametersToTypeParameterDeclarations(symbol *ast.Symbol) []*ast.Node { targetSymbol := b.ch.getTargetSymbol(symbol) if targetSymbol.Flags&(ast.SymbolFlagsClass|ast.SymbolFlagsInterface|ast.SymbolFlagsAlias) != 0 { var results []*ast.Node @@ -1549,7 +1549,7 @@ func getEffectiveParameterDeclaration(symbol *ast.Symbol) *ast.Node { return nil } -func (b *nodeBuilderImpl) symbolToParameterDeclaration(parameterSymbol *ast.Symbol, preserveModifierFlags bool) *ast.Node { +func (b *NodeBuilderImpl) symbolToParameterDeclaration(parameterSymbol *ast.Symbol, preserveModifierFlags bool) *ast.Node { parameterDeclaration := getEffectiveParameterDeclaration(parameterSymbol) parameterType := b.ch.getTypeOfSymbol(parameterSymbol) @@ -1587,7 +1587,7 @@ func (b *nodeBuilderImpl) symbolToParameterDeclaration(parameterSymbol *ast.Symb return parameterNode } -func (b *nodeBuilderImpl) parameterToParameterDeclarationName(parameterSymbol *ast.Symbol, parameterDeclaration *ast.Node) *ast.Node { +func (b *NodeBuilderImpl) parameterToParameterDeclarationName(parameterSymbol *ast.Symbol, parameterDeclaration *ast.Node) *ast.Node { if parameterDeclaration == nil || parameterDeclaration.Name() == nil { return b.f.NewIdentifier(parameterSymbol.Name) } @@ -1607,7 +1607,7 @@ func (b *nodeBuilderImpl) parameterToParameterDeclarationName(parameterSymbol *a } } -func (b *nodeBuilderImpl) cloneBindingName(node *ast.Node) *ast.Node { +func (b *NodeBuilderImpl) cloneBindingName(node *ast.Node) *ast.Node { if ast.IsComputedPropertyName(node) && b.ch.isLateBindableName(node) { b.trackComputedName(node.Expression(), b.ctx.enclosingDeclaration) } @@ -1633,17 +1633,17 @@ func (b *nodeBuilderImpl) cloneBindingName(node *ast.Node) *ast.Node { return visited } -func (b *nodeBuilderImpl) symbolTableToDeclarationStatements(symbolTable *ast.SymbolTable) []*ast.Node { +func (b *NodeBuilderImpl) symbolTableToDeclarationStatements(symbolTable *ast.SymbolTable) []*ast.Node { panic("unimplemented") // !!! } -func (b *nodeBuilderImpl) serializeTypeForExpression(expr *ast.Node) *ast.Node { +func (b *NodeBuilderImpl) serializeTypeForExpression(expr *ast.Node) *ast.Node { // !!! TODO: shim, add node reuse t := b.ch.instantiateType(b.ch.getWidenedType(b.ch.getRegularTypeOfExpression(expr)), b.ctx.mapper) return b.typeToTypeNode(t) } -func (b *nodeBuilderImpl) serializeInferredReturnTypeForSignature(signature *Signature, returnType *Type) *ast.Node { +func (b *NodeBuilderImpl) serializeInferredReturnTypeForSignature(signature *Signature, returnType *Type) *ast.Node { oldSuppressReportInferenceFallback := b.ctx.suppressReportInferenceFallback b.ctx.suppressReportInferenceFallback = true typePredicate := b.ch.getTypePredicateOfSignature(signature) @@ -1663,7 +1663,7 @@ func (b *nodeBuilderImpl) serializeInferredReturnTypeForSignature(signature *Sig return returnTypeNode } -func (b *nodeBuilderImpl) typePredicateToTypePredicateNodeHelper(typePredicate *TypePredicate) *ast.Node { +func (b *NodeBuilderImpl) typePredicateToTypePredicateNodeHelper(typePredicate *TypePredicate) *ast.Node { var assertsModifier *ast.Node if typePredicate.kind == TypePredicateKindAssertsThis || typePredicate.kind == TypePredicateKindAssertsIdentifier { assertsModifier = b.f.NewToken(ast.KindAssertsKeyword) @@ -1690,7 +1690,7 @@ type SignatureToSignatureDeclarationOptions struct { questionToken *ast.Node } -func (b *nodeBuilderImpl) signatureToSignatureDeclarationHelper(signature *Signature, kind ast.Kind, options *SignatureToSignatureDeclarationOptions) *ast.Node { +func (b *NodeBuilderImpl) signatureToSignatureDeclarationHelper(signature *Signature, kind ast.Kind, options *SignatureToSignatureDeclarationOptions) *ast.Node { var typeParameters []*ast.Node expandedParams := b.ch.getExpandedParameters(signature, true /*skipUnionExpanding*/)[0] @@ -1899,7 +1899,7 @@ func (c *Checker) getExpandedParameters(sig *Signature, skipUnionExpanding bool) return [][]*ast.Symbol{sig.parameters} } -func (b *nodeBuilderImpl) tryGetThisParameterDeclaration(signature *Signature) *ast.Node { +func (b *NodeBuilderImpl) tryGetThisParameterDeclaration(signature *Signature) *ast.Node { if signature.thisParameter != nil { return b.symbolToParameterDeclaration(signature.thisParameter, false) } @@ -1922,7 +1922,7 @@ func (b *nodeBuilderImpl) tryGetThisParameterDeclaration(signature *Signature) * /** * Serializes the return type of the signature by first trying to use the syntactic printer if possible and falling back to the checker type if not. */ -func (b *nodeBuilderImpl) serializeReturnTypeForSignature(signature *Signature) *ast.Node { +func (b *NodeBuilderImpl) serializeReturnTypeForSignature(signature *Signature) *ast.Node { suppressAny := b.ctx.flags&nodebuilder.FlagsSuppressAnyReturnType != 0 restoreFlags := b.saveRestoreFlags() if suppressAny { @@ -1951,7 +1951,7 @@ func (b *nodeBuilderImpl) serializeReturnTypeForSignature(signature *Signature) return returnTypeNode } -func (b *nodeBuilderImpl) indexInfoToIndexSignatureDeclarationHelper(indexInfo *IndexInfo, typeNode *ast.TypeNode) *ast.Node { +func (b *NodeBuilderImpl) indexInfoToIndexSignatureDeclarationHelper(indexInfo *IndexInfo, typeNode *ast.TypeNode) *ast.Node { name := getNameFromIndexInfo(indexInfo) indexerTypeNode := b.typeToTypeNode(indexInfo.keyType) @@ -1982,7 +1982,7 @@ func (b *nodeBuilderImpl) indexInfoToIndexSignatureDeclarationHelper(indexInfo * * @param type - The type to write; an existing annotation must match this type if it's used, otherwise this is the type serialized as a new type node * @param symbol - The symbol is used both to find an existing annotation if declaration is not provided, and to determine if `unique symbol` should be printed */ -func (b *nodeBuilderImpl) serializeTypeForDeclaration(declaration *ast.Declaration, t *Type, symbol *ast.Symbol) *ast.Node { +func (b *NodeBuilderImpl) serializeTypeForDeclaration(declaration *ast.Declaration, t *Type, symbol *ast.Symbol) *ast.Node { // !!! node reuse logic if symbol == nil { symbol = b.ch.getSymbolOfDeclaration(declaration) @@ -2019,7 +2019,7 @@ func (b *nodeBuilderImpl) serializeTypeForDeclaration(declaration *ast.Declarati const MAX_REVERSE_MAPPED_NESTING_INSPECTION_DEPTH = 3 -func (b *nodeBuilderImpl) shouldUsePlaceholderForProperty(propertySymbol *ast.Symbol) bool { +func (b *NodeBuilderImpl) shouldUsePlaceholderForProperty(propertySymbol *ast.Symbol) bool { // Use placeholders for reverse mapped types we've either // (1) already descended into, or // (2) are nested reverse mappings within a mapping over a non-anonymous type, or @@ -2080,7 +2080,7 @@ func (b *nodeBuilderImpl) shouldUsePlaceholderForProperty(propertySymbol *ast.Sy return false } -func (b *nodeBuilderImpl) trackComputedName(accessExpression *ast.Node, enclosingDeclaration *ast.Node) { +func (b *NodeBuilderImpl) trackComputedName(accessExpression *ast.Node, enclosingDeclaration *ast.Node) { // get symbol of the first identifier of the entityName firstIdentifier := ast.GetFirstIdentifier(accessExpression) name := b.ch.resolveName(firstIdentifier, firstIdentifier.Text(), ast.SymbolFlagsValue|ast.SymbolFlagsExportValue, nil /*nameNotFoundMessage*/, true /*isUse*/, false) @@ -2089,7 +2089,7 @@ func (b *nodeBuilderImpl) trackComputedName(accessExpression *ast.Node, enclosin } } -func (b *nodeBuilderImpl) createPropertyNameNodeForIdentifierOrLiteral(name string, singleQuote bool, stringNamed bool, isMethod bool) *ast.Node { +func (b *NodeBuilderImpl) createPropertyNameNodeForIdentifierOrLiteral(name string, singleQuote bool, stringNamed bool, isMethod bool) *ast.Node { isMethodNamedNew := isMethod && name == "new" if !isMethodNamedNew && scanner.IsIdentifierText(name, core.LanguageVariantStandard) { return b.f.NewIdentifier(name) @@ -2104,7 +2104,7 @@ func (b *nodeBuilderImpl) createPropertyNameNodeForIdentifierOrLiteral(name stri return result } -func (b *nodeBuilderImpl) isStringNamed(d *ast.Declaration) bool { +func (b *NodeBuilderImpl) isStringNamed(d *ast.Declaration) bool { name := ast.GetNameOfDeclaration(d) if name == nil { return false @@ -2120,12 +2120,12 @@ func (b *nodeBuilderImpl) isStringNamed(d *ast.Declaration) bool { return ast.IsStringLiteral(name) } -func (b *nodeBuilderImpl) isSingleQuotedStringNamed(d *ast.Declaration) bool { +func (b *NodeBuilderImpl) isSingleQuotedStringNamed(d *ast.Declaration) bool { name := ast.GetNameOfDeclaration(d) return name != nil && ast.IsStringLiteral(name) && name.AsStringLiteral().TokenFlags&ast.TokenFlagsSingleQuote != 0 } -func (b *nodeBuilderImpl) getPropertyNameNodeForSymbol(symbol *ast.Symbol) *ast.Node { +func (b *NodeBuilderImpl) getPropertyNameNodeForSymbol(symbol *ast.Symbol) *ast.Node { stringNamed := len(symbol.Declarations) != 0 && core.Every(symbol.Declarations, b.isStringNamed) singleQuote := len(symbol.Declarations) != 0 && core.Every(symbol.Declarations, b.isSingleQuotedStringNamed) isMethod := symbol.Flags&ast.SymbolFlagsMethod != 0 @@ -2147,7 +2147,7 @@ func (b *nodeBuilderImpl) getPropertyNameNodeForSymbol(symbol *ast.Symbol) *ast. } // See getNameForSymbolFromNameType for a stringy equivalent -func (b *nodeBuilderImpl) getPropertyNameNodeForSymbolFromNameType(symbol *ast.Symbol, singleQuote bool, stringNamed bool, isMethod bool) *ast.Node { +func (b *NodeBuilderImpl) getPropertyNameNodeForSymbolFromNameType(symbol *ast.Symbol, singleQuote bool, stringNamed bool, isMethod bool) *ast.Node { if !b.ch.valueSymbolLinks.Has(symbol) { return nil } @@ -2181,7 +2181,7 @@ func (b *nodeBuilderImpl) getPropertyNameNodeForSymbolFromNameType(symbol *ast.S return nil } -func (b *nodeBuilderImpl) addPropertyToElementList(propertySymbol *ast.Symbol, typeElements []*ast.TypeElement) []*ast.TypeElement { +func (b *NodeBuilderImpl) addPropertyToElementList(propertySymbol *ast.Symbol, typeElements []*ast.TypeElement) []*ast.TypeElement { propertyIsReverseMapped := propertySymbol.CheckFlags&ast.CheckFlagsReverseMapped != 0 var propertyType *Type if b.shouldUsePlaceholderForProperty(propertySymbol) { @@ -2315,7 +2315,7 @@ func (b *nodeBuilderImpl) addPropertyToElementList(propertySymbol *ast.Symbol, t return typeElements } -func (b *nodeBuilderImpl) createTypeNodesFromResolvedType(resolvedType *StructuredType) *ast.NodeList { +func (b *NodeBuilderImpl) createTypeNodesFromResolvedType(resolvedType *StructuredType) *ast.NodeList { if b.checkTruncationLength() { if b.ctx.flags&nodebuilder.FlagsNoTruncation != 0 { elem := b.f.NewNotEmittedTypeElement() @@ -2372,7 +2372,7 @@ func (b *nodeBuilderImpl) createTypeNodesFromResolvedType(resolvedType *Structur } } -func (b *nodeBuilderImpl) createTypeNodeFromObjectType(t *Type) *ast.TypeNode { +func (b *NodeBuilderImpl) createTypeNodeFromObjectType(t *Type) *ast.TypeNode { if b.ch.isGenericMappedType(t) || (t.objectFlags&ObjectFlagsMapped != 0 && t.AsMappedType().containsError) { return b.createMappedTypeNodeFromType(t) } @@ -2442,7 +2442,7 @@ func getTypeAliasForTypeLiteral(c *Checker, t *Type) *ast.Symbol { return nil } -func (b *nodeBuilderImpl) shouldWriteTypeOfFunctionSymbol(symbol *ast.Symbol, typeId TypeId) bool { +func (b *NodeBuilderImpl) shouldWriteTypeOfFunctionSymbol(symbol *ast.Symbol, typeId TypeId) bool { isStaticMethodSymbol := symbol.Flags&ast.SymbolFlagsMethod != 0 && core.Some(symbol.Declarations, func(declaration *ast.Node) bool { return ast.IsStatic(declaration) && !b.ch.isLateBindableIndexSignature(ast.GetNameOfDeclaration(declaration)) }) @@ -2467,7 +2467,7 @@ func (b *nodeBuilderImpl) shouldWriteTypeOfFunctionSymbol(symbol *ast.Symbol, ty return false } -func (b *nodeBuilderImpl) createAnonymousTypeNode(t *Type) *ast.TypeNode { +func (b *NodeBuilderImpl) createAnonymousTypeNode(t *Type) *ast.TypeNode { typeId := t.id symbol := t.symbol if symbol != nil { @@ -2484,7 +2484,7 @@ func (b *nodeBuilderImpl) createAnonymousTypeNode(t *Type) *ast.TypeNode { if b.ctx.visitedTypes.Has(typeId) { return b.createElidedInformationPlaceholder() } - return b.visitAndTransformType(t, (*nodeBuilderImpl).createTypeNodeFromObjectType) + return b.visitAndTransformType(t, (*NodeBuilderImpl).createTypeNodeFromObjectType) } var isInstanceType ast.SymbolFlags if isClassInstanceSide(b.ch, t) { @@ -2510,7 +2510,7 @@ func (b *nodeBuilderImpl) createAnonymousTypeNode(t *Type) *ast.TypeNode { return b.createElidedInformationPlaceholder() } } else { - return b.visitAndTransformType(t, (*nodeBuilderImpl).createTypeNodeFromObjectType) + return b.visitAndTransformType(t, (*NodeBuilderImpl).createTypeNodeFromObjectType) } } else { // Anonymous types without a symbol are never circular. @@ -2518,7 +2518,7 @@ func (b *nodeBuilderImpl) createAnonymousTypeNode(t *Type) *ast.TypeNode { } } -func (b *nodeBuilderImpl) getTypeFromTypeNode(node *ast.TypeNode, noMappedTypes bool) *Type { +func (b *NodeBuilderImpl) getTypeFromTypeNode(node *ast.TypeNode, noMappedTypes bool) *Type { // !!! noMappedTypes optional param support t := b.ch.getTypeFromTypeNode(node) if b.ctx.mapper == nil { @@ -2532,7 +2532,7 @@ func (b *nodeBuilderImpl) getTypeFromTypeNode(node *ast.TypeNode, noMappedTypes return instantiated } -func (b *nodeBuilderImpl) typeToTypeNodeOrCircularityElision(t *Type) *ast.TypeNode { +func (b *NodeBuilderImpl) typeToTypeNodeOrCircularityElision(t *Type) *ast.TypeNode { if t.flags&TypeFlagsUnion != 0 { if b.ctx.visitedTypes.Has(t.id) { if b.ctx.flags&nodebuilder.FlagsAllowAnonymousIdentifier == 0 { @@ -2541,12 +2541,12 @@ func (b *nodeBuilderImpl) typeToTypeNodeOrCircularityElision(t *Type) *ast.TypeN } return b.createElidedInformationPlaceholder() } - return b.visitAndTransformType(t, (*nodeBuilderImpl).typeToTypeNode) + return b.visitAndTransformType(t, (*NodeBuilderImpl).typeToTypeNode) } return b.typeToTypeNode(t) } -func (b *nodeBuilderImpl) conditionalTypeToTypeNode(_t *Type) *ast.TypeNode { +func (b *NodeBuilderImpl) conditionalTypeToTypeNode(_t *Type) *ast.TypeNode { t := _t.AsConditionalType() checkTypeNode := b.typeToTypeNode(t.checkType) b.ctx.approximateLength += 15 @@ -2589,7 +2589,7 @@ func (b *nodeBuilderImpl) conditionalTypeToTypeNode(_t *Type) *ast.TypeNode { return b.f.NewConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode) } -func (b *nodeBuilderImpl) getParentSymbolOfTypeParameter(typeParameter *TypeParameter) *ast.Symbol { +func (b *NodeBuilderImpl) getParentSymbolOfTypeParameter(typeParameter *TypeParameter) *ast.Symbol { tp := ast.GetDeclarationOfKind(typeParameter.symbol, ast.KindTypeParameter) var host *ast.Node // !!! JSDoc support @@ -2604,7 +2604,7 @@ func (b *nodeBuilderImpl) getParentSymbolOfTypeParameter(typeParameter *TypePara return b.ch.getSymbolOfNode(host) } -func (b *nodeBuilderImpl) typeReferenceToTypeNode(t *Type) *ast.TypeNode { +func (b *NodeBuilderImpl) typeReferenceToTypeNode(t *Type) *ast.TypeNode { var typeArguments []*Type = b.ch.getTypeArguments(t) if t.Target() == b.ch.globalArrayType || t.Target() == b.ch.globalReadonlyArrayType { if b.ctx.flags&nodebuilder.FlagsWriteArrayAsGenericType != 0 { @@ -2738,7 +2738,7 @@ func (b *nodeBuilderImpl) typeReferenceToTypeNode(t *Type) *ast.TypeNode { } } -func (b *nodeBuilderImpl) visitAndTransformType(t *Type, transform func(b *nodeBuilderImpl, t *Type) *ast.TypeNode) *ast.TypeNode { +func (b *NodeBuilderImpl) visitAndTransformType(t *Type, transform func(b *NodeBuilderImpl, t *Type) *ast.TypeNode) *ast.TypeNode { typeId := t.id isConstructorObject := t.objectFlags&ObjectFlagsAnonymous != 0 && t.symbol != nil && t.symbol.Flags&ast.SymbolFlagsClass != 0 var id *CompositeSymbolIdentity @@ -2823,7 +2823,7 @@ func (b *nodeBuilderImpl) visitAndTransformType(t *Type, transform func(b *nodeB // } } -func (b *nodeBuilderImpl) typeToTypeNode(t *Type) *ast.TypeNode { +func (b *NodeBuilderImpl) typeToTypeNode(t *Type) *ast.TypeNode { inTypeAlias := b.ctx.flags & nodebuilder.FlagsInTypeAlias b.ctx.flags &^= nodebuilder.FlagsInTypeAlias @@ -2984,7 +2984,7 @@ func (b *nodeBuilderImpl) typeToTypeNode(t *Type) *ast.TypeNode { if objectFlags&ObjectFlagsReference != 0 { debug.Assert(t.Flags()&TypeFlagsObject != 0) if t.AsTypeReference().node != nil { - return b.visitAndTransformType(t, (*nodeBuilderImpl).typeReferenceToTypeNode) + return b.visitAndTransformType(t, (*NodeBuilderImpl).typeReferenceToTypeNode) } else { return b.typeReferenceToTypeNode(t) } @@ -3090,7 +3090,7 @@ func (b *nodeBuilderImpl) typeToTypeNode(t *Type) *ast.TypeNode { return b.f.NewIndexedAccessTypeNode(objectTypeNode, indexTypeNode) } if t.flags&TypeFlagsConditional != 0 { - return b.visitAndTransformType(t, (*nodeBuilderImpl).conditionalTypeToTypeNode) + return b.visitAndTransformType(t, (*NodeBuilderImpl).conditionalTypeToTypeNode) } if t.flags&TypeFlagsSubstitution != 0 { typeNode := b.typeToTypeNode(t.AsSubstitutionType().baseType) @@ -3108,7 +3108,7 @@ func (b *nodeBuilderImpl) typeToTypeNode(t *Type) *ast.TypeNode { panic("Should be unreachable.") } -func (b *nodeBuilderImpl) newStringLiteral(text string) *ast.Node { +func (b *NodeBuilderImpl) newStringLiteral(text string) *ast.Node { node := b.f.NewStringLiteral(text) if b.ctx.flags&nodebuilder.FlagsUseSingleQuotesForStringLiteralType != 0 { node.AsStringLiteral().TokenFlags |= ast.TokenFlagsSingleQuote @@ -3118,6 +3118,6 @@ func (b *nodeBuilderImpl) newStringLiteral(text string) *ast.Node { // Direct serialization core functions for types, type aliases, and symbols -func (t *TypeAlias) ToTypeReferenceNode(b *nodeBuilderImpl) *ast.Node { +func (t *TypeAlias) ToTypeReferenceNode(b *NodeBuilderImpl) *ast.Node { return b.f.NewTypeReferenceNode(b.symbolToEntityNameNode(t.Symbol()), b.mapToTypeNodes(t.TypeArguments(), false /*isBareList*/)) } diff --git a/internal/checker/nodebuilderscopes.go b/internal/checker/nodebuilderscopes.go index 50f5dc2f17..4e7e9f0d33 100644 --- a/internal/checker/nodebuilderscopes.go +++ b/internal/checker/nodebuilderscopes.go @@ -49,7 +49,7 @@ type localsRecord struct { oldSymbol *ast.Symbol } -func (b *nodeBuilderImpl) enterNewScope(declaration *ast.Node, expandedParams []*ast.Symbol, typeParameters []*Type, originalParameters []*ast.Symbol, mapper *TypeMapper) func() { +func (b *NodeBuilderImpl) enterNewScope(declaration *ast.Node, expandedParams []*ast.Symbol, typeParameters []*Type, originalParameters []*ast.Symbol, mapper *TypeMapper) func() { cleanupContext := cloneNodeBuilderContext(b.ctx) // For regular function/method declarations, the enclosing declaration will already be signature.declaration, // so this is a no-op, but for arrow functions and function expressions, the enclosing declaration will be diff --git a/internal/compiler/fileInclude.go b/internal/compiler/fileInclude.go index 68687e5e03..13aeba9cd8 100644 --- a/internal/compiler/fileInclude.go +++ b/internal/compiler/fileInclude.go @@ -29,7 +29,7 @@ const ( fileIncludeKindAutomaticTypeDirectiveFile ) -type fileIncludeReason struct { +type FileIncludeReason struct { kind fileIncludeKind data any @@ -81,28 +81,28 @@ type automaticTypeDirectiveFileData struct { packageId module.PackageId } -func (r *fileIncludeReason) asIndex() int { +func (r *FileIncludeReason) asIndex() int { return r.data.(int) } -func (r *fileIncludeReason) asLibFileIndex() (int, bool) { +func (r *FileIncludeReason) asLibFileIndex() (int, bool) { index, ok := r.data.(int) return index, ok } -func (r *fileIncludeReason) isReferencedFile() bool { +func (r *FileIncludeReason) isReferencedFile() bool { return r != nil && r.kind <= fileIncludeKindLibReferenceDirective } -func (r *fileIncludeReason) asReferencedFileData() *referencedFileData { +func (r *FileIncludeReason) asReferencedFileData() *referencedFileData { return r.data.(*referencedFileData) } -func (r *fileIncludeReason) asAutomaticTypeDirectiveFileData() *automaticTypeDirectiveFileData { +func (r *FileIncludeReason) asAutomaticTypeDirectiveFileData() *automaticTypeDirectiveFileData { return r.data.(*automaticTypeDirectiveFileData) } -func (r *fileIncludeReason) getReferencedLocation(program *Program) *referenceFileLocation { +func (r *FileIncludeReason) getReferencedLocation(program *Program) *referenceFileLocation { ref := r.asReferencedFileData() file := program.GetSourceFileByPath(ref.file) switch r.kind { @@ -153,7 +153,7 @@ func (r *fileIncludeReason) getReferencedLocation(program *Program) *referenceFi } } -func (r *fileIncludeReason) toDiagnostic(program *Program, relativeFileName bool) *ast.Diagnostic { +func (r *FileIncludeReason) toDiagnostic(program *Program, relativeFileName bool) *ast.Diagnostic { if relativeFileName { r.relativeFileNameDiagOnce.Do(func() { r.relativeFileNameDiag = r.computeDiagnostic(program, func(fileName string) string { @@ -169,7 +169,7 @@ func (r *fileIncludeReason) toDiagnostic(program *Program, relativeFileName bool } } -func (r *fileIncludeReason) computeDiagnostic(program *Program, toFileName func(string) string) *ast.Diagnostic { +func (r *FileIncludeReason) computeDiagnostic(program *Program, toFileName func(string) string) *ast.Diagnostic { if r.isReferencedFile() { return r.computeReferenceFileDiagnostic(program, toFileName) } @@ -229,7 +229,7 @@ func (r *fileIncludeReason) computeDiagnostic(program *Program, toFileName func( } } -func (r *fileIncludeReason) computeReferenceFileDiagnostic(program *Program, toFileName func(string) string) *ast.Diagnostic { +func (r *FileIncludeReason) computeReferenceFileDiagnostic(program *Program, toFileName func(string) string) *ast.Diagnostic { referenceLocation := program.includeProcessor.getReferenceLocation(r, program) referenceText := referenceLocation.text() switch r.kind { @@ -268,7 +268,7 @@ func (r *fileIncludeReason) computeReferenceFileDiagnostic(program *Program, toF } } -func (r *fileIncludeReason) toRelatedInfo(program *Program) *ast.Diagnostic { +func (r *FileIncludeReason) toRelatedInfo(program *Program) *ast.Diagnostic { if r.isReferencedFile() { return r.computeReferenceFileRelatedInfo(program) } @@ -321,7 +321,7 @@ func (r *fileIncludeReason) toRelatedInfo(program *Program) *ast.Diagnostic { return nil } -func (r *fileIncludeReason) computeReferenceFileRelatedInfo(program *Program) *ast.Diagnostic { +func (r *FileIncludeReason) computeReferenceFileRelatedInfo(program *Program) *ast.Diagnostic { referenceLocation := program.includeProcessor.getReferenceLocation(r, program) if referenceLocation.isSynthetic { return nil diff --git a/internal/compiler/fileloader.go b/internal/compiler/fileloader.go index 9fbbc49057..bec5e1f725 100644 --- a/internal/compiler/fileloader.go +++ b/internal/compiler/fileloader.go @@ -106,19 +106,19 @@ func processAllProgramFiles( loader.addProjectReferenceTasks(singleThreaded) loader.resolver = module.NewResolver(loader.projectReferenceFileMapper.host, compilerOptions, opts.TypingsLocation, opts.ProjectName) for index, rootFile := range rootFiles { - loader.addRootTask(rootFile, nil, &fileIncludeReason{kind: fileIncludeKindRootFile, data: index}) + loader.addRootTask(rootFile, nil, &FileIncludeReason{kind: fileIncludeKindRootFile, data: index}) } if len(rootFiles) > 0 && compilerOptions.NoLib.IsFalseOrUnknown() { if compilerOptions.Lib == nil { name := tsoptions.GetDefaultLibFileName(compilerOptions) libFile := loader.pathForLibFile(name) - loader.addRootTask(libFile.path, libFile, &fileIncludeReason{kind: fileIncludeKindLibFile}) + loader.addRootTask(libFile.path, libFile, &FileIncludeReason{kind: fileIncludeKindLibFile}) } else { for index, lib := range compilerOptions.Lib { if name, ok := tsoptions.GetLibFileName(lib); ok { libFile := loader.pathForLibFile(name) - loader.addRootTask(libFile.path, libFile, &fileIncludeReason{kind: fileIncludeKindLibFile, data: index}) + loader.addRootTask(libFile.path, libFile, &FileIncludeReason{kind: fileIncludeKindLibFile, data: index}) } // !!! error on unknown name } @@ -142,7 +142,7 @@ func processAllProgramFiles( libFiles := make([]*ast.SourceFile, 0, totalFileCount) // totalFileCount here since we append files to it later to construct the final list filesByPath := make(map[tspath.Path]*ast.SourceFile, totalFileCount) - loader.includeProcessor.fileIncludeReasons = make(map[tspath.Path][]*fileIncludeReason, totalFileCount) + loader.includeProcessor.fileIncludeReasons = make(map[tspath.Path][]*FileIncludeReason, totalFileCount) var outputFileToProjectReferenceSource map[tspath.Path]string if !opts.canUseProjectReferenceSource() { outputFileToProjectReferenceSource = make(map[tspath.Path]string, totalFileCount) @@ -264,7 +264,7 @@ func (p *fileLoader) toPath(file string) tspath.Path { return tspath.ToPath(file, p.opts.Host.GetCurrentDirectory(), p.opts.Host.FS().UseCaseSensitiveFileNames()) } -func (p *fileLoader) addRootTask(fileName string, libFile *LibFile, includeReason *fileIncludeReason) { +func (p *fileLoader) addRootTask(fileName string, libFile *LibFile, includeReason *FileIncludeReason) { absPath := tspath.GetNormalizedAbsolutePath(fileName, p.opts.Host.GetCurrentDirectory()) if core.Tristate.IsTrue(p.opts.Config.CompilerOptions().AllowNonTsExtensions) || slices.Contains(p.supportedExtensions, tspath.TryGetExtensionFromPath(absPath)) { p.rootTasks = append(p.rootTasks, &parseTask{ @@ -309,7 +309,7 @@ func (p *fileLoader) resolveAutomaticTypeDirectives(containingFileName string) ( fileName: resolved.ResolvedFileName, increaseDepth: resolved.IsExternalLibraryImport, elideOnDepth: false, - includeReason: &fileIncludeReason{ + includeReason: &FileIncludeReason{ kind: fileIncludeKindAutomaticTypeDirectiveFile, data: &automaticTypeDirectiveFileData{name, resolved.PackageId}, }, @@ -350,7 +350,7 @@ func (p *fileLoader) addProjectReferenceTasks(singleThreaded bool) { for _, fileName := range resolved.FileNames() { p.rootTasks = append(p.rootTasks, &parseTask{ normalizedFilePath: fileName, - includeReason: &fileIncludeReason{ + includeReason: &FileIncludeReason{ kind: fileIncludeKindSourceFromProjectReference, data: index, }, @@ -361,7 +361,7 @@ func (p *fileLoader) addProjectReferenceTasks(singleThreaded bool) { if outputDts != "" { p.rootTasks = append(p.rootTasks, &parseTask{ normalizedFilePath: outputDts, - includeReason: &fileIncludeReason{ + includeReason: &FileIncludeReason{ kind: fileIncludeKindOutputFromProjectReference, data: index, }, @@ -438,7 +438,7 @@ func (p *fileLoader) resolveTripleslashPathReference(moduleName string, containi } return resolvedRef{ fileName: tspath.NormalizePath(referencedFileName), - includeReason: &fileIncludeReason{ + includeReason: &FileIncludeReason{ kind: fileIncludeKindReferenceFile, data: &referencedFileData{ file: p.toPath(containingFile), @@ -462,7 +462,7 @@ func (p *fileLoader) resolveTypeReferenceDirectives(t *parseTask) { resolutionMode := getModeForTypeReferenceDirectiveInFile(ref, file, meta, module.GetCompilerOptionsWithRedirect(p.opts.Config.CompilerOptions(), redirect)) resolved, trace := p.resolver.ResolveTypeReferenceDirective(ref.FileName, fileName, resolutionMode, redirect) typeResolutionsInFile[module.ModeAwareCacheKey{Name: ref.FileName, Mode: resolutionMode}] = resolved - includeReason := &fileIncludeReason{ + includeReason := &FileIncludeReason{ kind: fileIncludeKindTypeReferenceDirective, data: &referencedFileData{ file: t.path, @@ -577,7 +577,7 @@ func (p *fileLoader) resolveImportsAndModuleAugmentations(t *parseTask) { increaseDepth: resolvedModule.IsExternalLibraryImport, elideOnDepth: isJsFileFromNodeModules, isFromExternalLibrary: resolvedModule.IsExternalLibraryImport, - includeReason: &fileIncludeReason{ + includeReason: &FileIncludeReason{ kind: fileIncludeKindImport, data: &referencedFileData{ file: t.path, diff --git a/internal/compiler/filesparser.go b/internal/compiler/filesparser.go index d0fb499a67..abf767ed34 100644 --- a/internal/compiler/filesparser.go +++ b/internal/compiler/filesparser.go @@ -21,7 +21,7 @@ type parseTask struct { subTasks []*parseTask loaded bool isForAutomaticTypeDirective bool - includeReason *fileIncludeReason + includeReason *FileIncludeReason metadata ast.SourceFileMetaData resolutionsInFile module.ModeAwareCache[*module.ResolvedModule] @@ -39,7 +39,7 @@ type parseTask struct { fromExternalLibrary bool loadedTask *parseTask - allIncludeReasons []*fileIncludeReason + allIncludeReasons []*FileIncludeReason } func (t *parseTask) FileName() string { @@ -92,7 +92,7 @@ func (t *parseTask) load(loader *fileLoader) { if compilerOptions.NoLib != core.TSTrue { for index, lib := range file.LibReferenceDirectives { - includeReason := &fileIncludeReason{ + includeReason := &FileIncludeReason{ kind: fileIncludeKindLibReferenceDirective, data: &referencedFileData{ file: t.path, @@ -142,7 +142,7 @@ type resolvedRef struct { increaseDepth bool elideOnDepth bool isFromExternalLibrary bool - includeReason *fileIncludeReason + includeReason *FileIncludeReason } func (t *parseTask) addSubTask(ref resolvedRef, libFile *LibFile) { @@ -267,14 +267,14 @@ func (w *filesParser) collectWorker(loader *fileLoader, tasks []*parseTask, iter } } -func (w *filesParser) addIncludeReason(loader *fileLoader, task *parseTask, reason *fileIncludeReason) { +func (w *filesParser) addIncludeReason(loader *fileLoader, task *parseTask, reason *FileIncludeReason) { if task.redirectedParseTask != nil { w.addIncludeReason(loader, task.redirectedParseTask, reason) } else if task.loaded { if existing, ok := loader.includeProcessor.fileIncludeReasons[task.path]; ok { loader.includeProcessor.fileIncludeReasons[task.path] = append(existing, reason) } else { - loader.includeProcessor.fileIncludeReasons[task.path] = []*fileIncludeReason{reason} + loader.includeProcessor.fileIncludeReasons[task.path] = []*FileIncludeReason{reason} } } } diff --git a/internal/compiler/includeprocessor.go b/internal/compiler/includeprocessor.go index d865d74fbb..83691f45a1 100644 --- a/internal/compiler/includeprocessor.go +++ b/internal/compiler/includeprocessor.go @@ -12,11 +12,11 @@ import ( ) type includeProcessor struct { - fileIncludeReasons map[tspath.Path][]*fileIncludeReason + fileIncludeReasons map[tspath.Path][]*FileIncludeReason processingDiagnostics []*processingDiagnostic - reasonToReferenceLocation collections.SyncMap[*fileIncludeReason, *referenceFileLocation] - includeReasonToRelatedInfo collections.SyncMap[*fileIncludeReason, *ast.Diagnostic] + reasonToReferenceLocation collections.SyncMap[*FileIncludeReason, *referenceFileLocation] + includeReasonToRelatedInfo collections.SyncMap[*FileIncludeReason, *ast.Diagnostic] redirectAndFileFormat collections.SyncMap[tspath.Path, []*ast.Diagnostic] computedDiagnostics *ast.DiagnosticsCollection computedDiagnosticsOnce sync.Once @@ -59,7 +59,7 @@ func (i *includeProcessor) addProcessingDiagnostic(d ...*processingDiagnostic) { i.processingDiagnostics = append(i.processingDiagnostics, d...) } -func (i *includeProcessor) getReferenceLocation(r *fileIncludeReason, program *Program) *referenceFileLocation { +func (i *includeProcessor) getReferenceLocation(r *FileIncludeReason, program *Program) *referenceFileLocation { if existing, ok := i.reasonToReferenceLocation.Load(r); ok { return existing } @@ -84,7 +84,7 @@ func (i *includeProcessor) getCompilerOptionsObjectLiteralSyntax(program *Progra return i.compilerOptionsSyntax } -func (i *includeProcessor) getRelatedInfo(r *fileIncludeReason, program *Program) *ast.Diagnostic { +func (i *includeProcessor) getRelatedInfo(r *FileIncludeReason, program *Program) *ast.Diagnostic { if existing, ok := i.includeReasonToRelatedInfo.Load(r); ok { return existing } diff --git a/internal/compiler/processingDiagnostic.go b/internal/compiler/processingDiagnostic.go index 83bac967ab..20e5c8d18c 100644 --- a/internal/compiler/processingDiagnostic.go +++ b/internal/compiler/processingDiagnostic.go @@ -23,13 +23,13 @@ type processingDiagnostic struct { data any } -func (d *processingDiagnostic) asFileIncludeReason() *fileIncludeReason { - return d.data.(*fileIncludeReason) +func (d *processingDiagnostic) asFileIncludeReason() *FileIncludeReason { + return d.data.(*FileIncludeReason) } type includeExplainingDiagnostic struct { file tspath.Path - diagnosticReason *fileIncludeReason + diagnosticReason *FileIncludeReason message *diagnostics.Message args []any } @@ -70,13 +70,13 @@ func (d *processingDiagnostic) createDiagnosticExplainingFile(program *Program) var includeDetails []*ast.Diagnostic var relatedInfo []*ast.Diagnostic var redirectInfo []*ast.Diagnostic - var preferredLocation *fileIncludeReason - var seenReasons collections.Set[*fileIncludeReason] + var preferredLocation *FileIncludeReason + var seenReasons collections.Set[*FileIncludeReason] if diag.diagnosticReason.isReferencedFile() && !program.includeProcessor.getReferenceLocation(diag.diagnosticReason, program).isSynthetic { preferredLocation = diag.diagnosticReason } - processRelatedInfo := func(includeReason *fileIncludeReason) { + processRelatedInfo := func(includeReason *FileIncludeReason) { if preferredLocation == nil && includeReason.isReferencedFile() && !program.includeProcessor.getReferenceLocation(includeReason, program).isSynthetic { preferredLocation = includeReason } else { @@ -86,7 +86,7 @@ func (d *processingDiagnostic) createDiagnosticExplainingFile(program *Program) } } } - processInclude := func(includeReason *fileIncludeReason) { + processInclude := func(includeReason *FileIncludeReason) { if !seenReasons.AddIfAbsent(includeReason) { return } diff --git a/internal/compiler/program.go b/internal/compiler/program.go index 794d2fa96d..6d9fdf95d1 100644 --- a/internal/compiler/program.go +++ b/internal/compiler/program.go @@ -1538,7 +1538,7 @@ func (p *Program) GetSourceFiles() []*ast.SourceFile { } // Testing only -func (p *Program) GetIncludeReasons() map[tspath.Path][]*fileIncludeReason { +func (p *Program) GetIncludeReasons() map[tspath.Path][]*FileIncludeReason { return p.includeProcessor.fileIncludeReasons } diff --git a/internal/execute/build/buildtask.go b/internal/execute/build/buildtask.go index 72b58fd7a9..2638fd240a 100644 --- a/internal/execute/build/buildtask.go +++ b/internal/execute/build/buildtask.go @@ -36,7 +36,7 @@ const ( ) type upstreamTask struct { - task *buildTask + task *BuildTask refIndex int } type buildInfoEntry struct { @@ -57,17 +57,17 @@ type taskResult struct { filesToDelete []string } -type buildTask struct { +type BuildTask struct { config string resolved *tsoptions.ParsedCommandLine upStream []*upstreamTask - downStream []*buildTask // Only set and used in watch mode + downStream []*BuildTask // Only set and used in watch mode status *upToDateStatus done chan struct{} // task reporting result *taskResult - prevReporter *buildTask + prevReporter *BuildTask reportDone chan struct{} // Watching things @@ -85,24 +85,24 @@ type buildTask struct { dirty bool } -func (t *buildTask) waitOnUpstream() { +func (t *BuildTask) waitOnUpstream() { for _, upstream := range t.upStream { <-upstream.task.done } } -func (t *buildTask) unblockDownstream() { +func (t *BuildTask) unblockDownstream() { t.pending.Store(false) t.isInitialCycle = false close(t.done) } -func (t *buildTask) reportDiagnostic(err *ast.Diagnostic) { +func (t *BuildTask) reportDiagnostic(err *ast.Diagnostic) { t.errors = append(t.errors, err) t.result.diagnosticReporter(err) } -func (t *buildTask) report(orchestrator *Orchestrator, configPath tspath.Path, buildResult *orchestratorResult) { +func (t *BuildTask) report(orchestrator *Orchestrator, configPath tspath.Path, buildResult *orchestratorResult) { if t.prevReporter != nil { <-t.prevReporter.reportDone } @@ -132,7 +132,7 @@ func (t *buildTask) report(orchestrator *Orchestrator, configPath tspath.Path, b close(t.reportDone) } -func (t *buildTask) buildProject(orchestrator *Orchestrator, path tspath.Path) { +func (t *BuildTask) buildProject(orchestrator *Orchestrator, path tspath.Path) { // Wait on upstream tasks to complete t.waitOnUpstream() if t.pending.Load() { @@ -163,7 +163,7 @@ func (t *buildTask) buildProject(orchestrator *Orchestrator, path tspath.Path) { t.unblockDownstream() } -func (t *buildTask) updateDownstream(orchestrator *Orchestrator, path tspath.Path) { +func (t *BuildTask) updateDownstream(orchestrator *Orchestrator, path tspath.Path) { if t.isInitialCycle { return } @@ -199,7 +199,7 @@ func (t *buildTask) updateDownstream(orchestrator *Orchestrator, path tspath.Pat } } -func (t *buildTask) compileAndEmit(orchestrator *Orchestrator, path tspath.Path) { +func (t *BuildTask) compileAndEmit(orchestrator *Orchestrator, path tspath.Path) { t.errors = nil if orchestrator.opts.Command.BuildOptions.Verbose.IsTrue() { t.result.reportStatus(ast.NewCompilerDiagnostic(diagnostics.Building_project_0, orchestrator.relativeFileName(t.config))) @@ -265,7 +265,7 @@ func (t *buildTask) compileAndEmit(orchestrator *Orchestrator, path tspath.Path) } } -func (t *buildTask) handleStatusThatDoesntRequireBuild(orchestrator *Orchestrator) bool { +func (t *BuildTask) handleStatusThatDoesntRequireBuild(orchestrator *Orchestrator) bool { switch t.status.kind { case upToDateStatusTypeUpToDate: if orchestrator.opts.Command.BuildOptions.Dry.IsTrue() { @@ -315,7 +315,7 @@ func (t *buildTask) handleStatusThatDoesntRequireBuild(orchestrator *Orchestrato return false } -func (t *buildTask) getUpToDateStatus(orchestrator *Orchestrator, configPath tspath.Path) *upToDateStatus { +func (t *BuildTask) getUpToDateStatus(orchestrator *Orchestrator, configPath tspath.Path) *upToDateStatus { if t.status != nil { return t.status } @@ -527,7 +527,7 @@ func (t *buildTask) getUpToDateStatus(orchestrator *Orchestrator, configPath tsp } } -func (t *buildTask) reportUpToDateStatus(orchestrator *Orchestrator) { +func (t *BuildTask) reportUpToDateStatus(orchestrator *Orchestrator) { if !orchestrator.opts.Command.BuildOptions.Verbose.IsTrue() { return } @@ -639,11 +639,11 @@ func (t *buildTask) reportUpToDateStatus(orchestrator *Orchestrator) { } } -func (t *buildTask) canUpdateJsDtsOutputTimestamps() bool { +func (t *BuildTask) canUpdateJsDtsOutputTimestamps() bool { return !t.resolved.CompilerOptions().NoEmit.IsTrue() && !t.resolved.CompilerOptions().IsIncremental() } -func (t *buildTask) updateTimeStamps(orchestrator *Orchestrator, emittedFiles []string, verboseMessage *diagnostics.Message) { +func (t *BuildTask) updateTimeStamps(orchestrator *Orchestrator, emittedFiles []string, verboseMessage *diagnostics.Message) { emitted := collections.NewSetFromItems(emittedFiles...) var verboseMessageReported bool buildInfoName := t.resolved.GetBuildInfoFileName() @@ -678,7 +678,7 @@ func (t *buildTask) updateTimeStamps(orchestrator *Orchestrator, emittedFiles [] updateTimeStamp(t.resolved.GetBuildInfoFileName()) } -func (t *buildTask) cleanProject(orchestrator *Orchestrator, path tspath.Path) { +func (t *BuildTask) cleanProject(orchestrator *Orchestrator, path tspath.Path) { if t.resolved == nil { t.reportDiagnostic(ast.NewCompilerDiagnostic(diagnostics.File_0_not_found, t.config)) t.result.exitStatus = tsc.ExitStatusDiagnosticsPresent_OutputsSkipped @@ -692,7 +692,7 @@ func (t *buildTask) cleanProject(orchestrator *Orchestrator, path tspath.Path) { t.cleanProjectOutput(orchestrator, t.resolved.GetBuildInfoFileName(), inputs) } -func (t *buildTask) cleanProjectOutput(orchestrator *Orchestrator, outputFile string, inputs *collections.Set[tspath.Path]) { +func (t *BuildTask) cleanProjectOutput(orchestrator *Orchestrator, outputFile string, inputs *collections.Set[tspath.Path]) { outputPath := orchestrator.toPath(outputFile) // If output name is same as input file name, do not delete and ignore the error if inputs.Has(outputPath) { @@ -710,7 +710,7 @@ func (t *buildTask) cleanProjectOutput(orchestrator *Orchestrator, outputFile st } } -func (t *buildTask) updateWatch(orchestrator *Orchestrator, oldCache *collections.SyncMap[tspath.Path, time.Time]) { +func (t *BuildTask) updateWatch(orchestrator *Orchestrator, oldCache *collections.SyncMap[tspath.Path, time.Time]) { t.configTime = orchestrator.host.loadOrStoreMTime(t.config, oldCache, false) if t.resolved != nil { t.extendedConfigTimes = core.Map(t.resolved.ExtendedSourceFiles(), func(p string) time.Time { @@ -727,18 +727,18 @@ func (t *buildTask) updateWatch(orchestrator *Orchestrator, oldCache *collection } } -func (t *buildTask) resetStatus() { +func (t *BuildTask) resetStatus() { t.status = nil t.pending.Store(true) t.errors = nil } -func (t *buildTask) resetConfig(orchestrator *Orchestrator, path tspath.Path) { +func (t *BuildTask) resetConfig(orchestrator *Orchestrator, path tspath.Path) { t.dirty = true orchestrator.host.resolvedReferences.delete(path) } -func (t *buildTask) hasUpdate(orchestrator *Orchestrator, path tspath.Path) updateKind { +func (t *BuildTask) hasUpdate(orchestrator *Orchestrator, path tspath.Path) updateKind { var needsConfigUpdate bool var needsUpdate bool if configTime := orchestrator.host.GetMTime(t.config); configTime != t.configTime { @@ -777,7 +777,7 @@ func (t *buildTask) hasUpdate(orchestrator *Orchestrator, path tspath.Path) upda return core.IfElse(needsConfigUpdate, updateKindConfig, core.IfElse(needsUpdate, updateKindUpdate, updateKindNone)) } -func (t *buildTask) loadOrStoreBuildInfo(orchestrator *Orchestrator, configPath tspath.Path, buildInfoFileName string) (*incremental.BuildInfo, time.Time) { +func (t *BuildTask) loadOrStoreBuildInfo(orchestrator *Orchestrator, configPath tspath.Path, buildInfoFileName string) (*incremental.BuildInfo, time.Time) { path := orchestrator.toPath(buildInfoFileName) t.buildInfoEntryMu.Lock() defer t.buildInfoEntryMu.Unlock() @@ -796,7 +796,7 @@ func (t *buildTask) loadOrStoreBuildInfo(orchestrator *Orchestrator, configPath return t.buildInfoEntry.buildInfo, mTime } -func (t *buildTask) onBuildInfoEmit(orchestrator *Orchestrator, buildInfoFileName string, buildInfo *incremental.BuildInfo, hasChangedDtsFile bool) { +func (t *BuildTask) onBuildInfoEmit(orchestrator *Orchestrator, buildInfoFileName string, buildInfo *incremental.BuildInfo, hasChangedDtsFile bool) { t.buildInfoEntryMu.Lock() defer t.buildInfoEntryMu.Unlock() var dtsTime *time.Time @@ -814,14 +814,14 @@ func (t *buildTask) onBuildInfoEmit(orchestrator *Orchestrator, buildInfoFileNam } } -func (t *buildTask) hasConflictingBuildInfo(orchestrator *Orchestrator, upstream *buildTask) bool { +func (t *BuildTask) hasConflictingBuildInfo(orchestrator *Orchestrator, upstream *BuildTask) bool { if t.buildInfoEntry != nil && upstream.buildInfoEntry != nil { return t.buildInfoEntry.path == upstream.buildInfoEntry.path } return false } -func (t *buildTask) getLatestChangedDtsMTime(orchestrator *Orchestrator) time.Time { +func (t *BuildTask) getLatestChangedDtsMTime(orchestrator *Orchestrator) time.Time { t.buildInfoEntryMu.Lock() defer t.buildInfoEntryMu.Unlock() if t.buildInfoEntry.dtsTime != nil { @@ -837,11 +837,11 @@ func (t *buildTask) getLatestChangedDtsMTime(orchestrator *Orchestrator) time.Ti return dtsTime } -func (t *buildTask) storeOutputTimeStamp(orchestrator *Orchestrator) bool { +func (t *BuildTask) storeOutputTimeStamp(orchestrator *Orchestrator) bool { return orchestrator.opts.Command.CompilerOptions.Watch.IsTrue() && !t.resolved.CompilerOptions().IsIncremental() } -func (t *buildTask) writeFile(orchestrator *Orchestrator, fileName string, text string, writeByteOrderMark bool, data *compiler.WriteFileData) error { +func (t *BuildTask) writeFile(orchestrator *Orchestrator, fileName string, text string, writeByteOrderMark bool, data *compiler.WriteFileData) error { err := orchestrator.host.FS().WriteFile(fileName, text, writeByteOrderMark) if err == nil { if data != nil && data.BuildInfo != nil { diff --git a/internal/execute/build/orchestrator.go b/internal/execute/build/orchestrator.go index d521031780..f89f39d3f3 100644 --- a/internal/execute/build/orchestrator.go +++ b/internal/execute/build/orchestrator.go @@ -58,7 +58,7 @@ type Orchestrator struct { host *host // order generation result - tasks *collections.SyncMap[tspath.Path, *buildTask] + tasks *collections.SyncMap[tspath.Path, *BuildTask] order []string errors []*ast.Diagnostic @@ -91,12 +91,12 @@ func (o *Orchestrator) Upstream(configName string) []string { func (o *Orchestrator) Downstream(configName string) []string { path := o.toPath(configName) task := o.getTask(path) - return core.Map(task.downStream, func(t *buildTask) string { + return core.Map(task.downStream, func(t *BuildTask) string { return t.config }) } -func (o *Orchestrator) getTask(path tspath.Path) *buildTask { +func (o *Orchestrator) getTask(path tspath.Path) *BuildTask { task, ok := o.tasks.Load(path) if !ok { panic("No build task found for " + path) @@ -104,11 +104,11 @@ func (o *Orchestrator) getTask(path tspath.Path) *buildTask { return task } -func (o *Orchestrator) createBuildTasks(oldTasks *collections.SyncMap[tspath.Path, *buildTask], configs []string, wg core.WorkGroup) { +func (o *Orchestrator) createBuildTasks(oldTasks *collections.SyncMap[tspath.Path, *BuildTask], configs []string, wg core.WorkGroup) { for _, config := range configs { wg.Queue(func() { path := o.toPath(config) - var task *buildTask + var task *BuildTask var buildInfo *buildInfoEntry if oldTasks != nil { if existing, ok := oldTasks.Load(path); ok { @@ -121,7 +121,7 @@ func (o *Orchestrator) createBuildTasks(oldTasks *collections.SyncMap[tspath.Pat } } if task == nil { - task = &buildTask{config: config, isInitialCycle: oldTasks == nil} + task = &BuildTask{config: config, isInitialCycle: oldTasks == nil} task.pending.Store(true) task.buildInfoEntry = buildInfo } @@ -139,12 +139,12 @@ func (o *Orchestrator) createBuildTasks(oldTasks *collections.SyncMap[tspath.Pat func (o *Orchestrator) setupBuildTask( configName string, - downStream *buildTask, + downStream *BuildTask, inCircularContext bool, completed *collections.Set[tspath.Path], analyzing *collections.Set[tspath.Path], circularityStack []string, -) *buildTask { +) *BuildTask { path := o.toPath(configName) task := o.getTask(path) if !completed.Has(path) { @@ -185,13 +185,13 @@ func (o *Orchestrator) setupBuildTask( func (o *Orchestrator) GenerateGraphReusingOldTasks() { tasks := o.tasks - o.tasks = &collections.SyncMap[tspath.Path, *buildTask]{} + o.tasks = &collections.SyncMap[tspath.Path, *BuildTask]{} o.order = nil o.errors = nil o.GenerateGraph(tasks) } -func (o *Orchestrator) GenerateGraph(oldTasks *collections.SyncMap[tspath.Path, *buildTask]) { +func (o *Orchestrator) GenerateGraph(oldTasks *collections.SyncMap[tspath.Path, *BuildTask]) { projects := o.opts.Command.ResolvedProjectPaths() // Parse all config files in parallel wg := core.NewWorkGroup(o.opts.Command.CompilerOptions.SingleThreaded.IsTrue()) @@ -239,7 +239,7 @@ func (o *Orchestrator) updateWatch() { oldCache := o.host.mTimes o.host.mTimes = &collections.SyncMap[tspath.Path, time.Time]{} wg := core.NewWorkGroup(o.opts.Command.CompilerOptions.SingleThreaded.IsTrue()) - o.tasks.Range(func(path tspath.Path, task *buildTask) bool { + o.tasks.Range(func(path tspath.Path, task *BuildTask) bool { wg.Queue(func() { task.updateWatch(o, oldCache) }) @@ -262,7 +262,7 @@ func (o *Orchestrator) DoCycle() { var needsUpdate atomic.Bool mTimes := o.host.mTimes.Clone() wg := core.NewWorkGroup(o.opts.Command.CompilerOptions.SingleThreaded.IsTrue()) - o.tasks.Range(func(path tspath.Path, task *buildTask) bool { + o.tasks.Range(func(path tspath.Path, task *BuildTask) bool { wg.Queue(func() { if updateKind := task.hasUpdate(o, path); updateKind != updateKindNone { needsUpdate.Store(true) @@ -335,7 +335,7 @@ func (o *Orchestrator) singleThreadedBuildOrClean(buildResult *orchestratorResul func (o *Orchestrator) multiThreadedBuildOrClean(buildResult *orchestratorResult) { // Spin off the threads with waiting on upstream to build before actual project build wg := core.NewWorkGroup(false) - o.tasks.Range(func(path tspath.Path, task *buildTask) bool { + o.tasks.Range(func(path tspath.Path, task *BuildTask) bool { wg.Queue(func() { o.buildOrCleanProject(task, path, buildResult) }) @@ -344,7 +344,7 @@ func (o *Orchestrator) multiThreadedBuildOrClean(buildResult *orchestratorResult wg.RunAndWait() } -func (o *Orchestrator) buildOrCleanProject(task *buildTask, path tspath.Path, buildResult *orchestratorResult) { +func (o *Orchestrator) buildOrCleanProject(task *BuildTask, path tspath.Path, buildResult *orchestratorResult) { task.result = &taskResult{} task.result.reportStatus = o.createBuilderStatusReporter(task) task.result.diagnosticReporter = o.createDiagnosticReporter(task) @@ -356,18 +356,18 @@ func (o *Orchestrator) buildOrCleanProject(task *buildTask, path tspath.Path, bu task.report(o, path, buildResult) } -func (o *Orchestrator) getWriter(task *buildTask) io.Writer { +func (o *Orchestrator) getWriter(task *BuildTask) io.Writer { if task == nil { return o.opts.Sys.Writer() } return &task.result.builder } -func (o *Orchestrator) createBuilderStatusReporter(task *buildTask) tsc.DiagnosticReporter { +func (o *Orchestrator) createBuilderStatusReporter(task *BuildTask) tsc.DiagnosticReporter { return tsc.CreateBuilderStatusReporter(o.opts.Sys, o.getWriter(task), o.opts.Command.CompilerOptions, o.opts.Testing) } -func (o *Orchestrator) createDiagnosticReporter(task *buildTask) tsc.DiagnosticReporter { +func (o *Orchestrator) createDiagnosticReporter(task *BuildTask) tsc.DiagnosticReporter { return tsc.CreateDiagnosticReporter(o.opts.Sys, o.getWriter(task), o.opts.Command.CompilerOptions) } @@ -378,7 +378,7 @@ func NewOrchestrator(opts Options) *Orchestrator { CurrentDirectory: opts.Sys.GetCurrentDirectory(), UseCaseSensitiveFileNames: opts.Sys.FS().UseCaseSensitiveFileNames(), }, - tasks: &collections.SyncMap[tspath.Path, *buildTask]{}, + tasks: &collections.SyncMap[tspath.Path, *BuildTask]{}, } orchestrator.host = &host{ orchestrator: orchestrator, diff --git a/internal/execute/incremental/buildInfo.go b/internal/execute/incremental/buildInfo.go index ab5b622363..36cfb0a9ca 100644 --- a/internal/execute/incremental/buildInfo.go +++ b/internal/execute/incremental/buildInfo.go @@ -92,7 +92,7 @@ type BuildInfoFileInfo struct { fileInfo *buildInfoFileInfoWithSignature } -func newBuildInfoFileInfo(fileInfo *fileInfo) *BuildInfoFileInfo { +func newBuildInfoFileInfo(fileInfo *FileInfo) *BuildInfoFileInfo { if fileInfo.version == fileInfo.signature { if !fileInfo.affectsGlobalScope && fileInfo.impliedNodeFormat == core.ResolutionModeCommonJS { return &BuildInfoFileInfo{signature: fileInfo.signature} @@ -113,25 +113,25 @@ func newBuildInfoFileInfo(fileInfo *fileInfo) *BuildInfoFileInfo { }} } -func (b *BuildInfoFileInfo) GetFileInfo() *fileInfo { +func (b *BuildInfoFileInfo) GetFileInfo() *FileInfo { if b == nil { return nil } if b.signature != "" { - return &fileInfo{ + return &FileInfo{ version: b.signature, signature: b.signature, impliedNodeFormat: core.ResolutionModeCommonJS, } } if b.noSignature != nil { - return &fileInfo{ + return &FileInfo{ version: b.noSignature.Version, affectsGlobalScope: b.noSignature.AffectsGlobalScope, impliedNodeFormat: b.noSignature.ImpliedNodeFormat, } } - return &fileInfo{ + return &FileInfo{ version: b.fileInfo.Version, signature: core.IfElse(b.fileInfo.Signature == "", b.fileInfo.Version, b.fileInfo.Signature), affectsGlobalScope: b.fileInfo.AffectsGlobalScope, diff --git a/internal/execute/incremental/buildinfotosnapshot.go b/internal/execute/incremental/buildinfotosnapshot.go index 10ebb40f64..ba11a95cc5 100644 --- a/internal/execute/incremental/buildinfotosnapshot.go +++ b/internal/execute/incremental/buildinfotosnapshot.go @@ -89,8 +89,8 @@ func (t *toSnapshot) toBuildInfoDiagnosticsWithFileName(diagnostics []*BuildInfo }) } -func (t *toSnapshot) toDiagnosticsOrBuildInfoDiagnosticsWithFileName(dig *BuildInfoDiagnosticsOfFile) *diagnosticsOrBuildInfoDiagnosticsWithFileName { - return &diagnosticsOrBuildInfoDiagnosticsWithFileName{ +func (t *toSnapshot) toDiagnosticsOrBuildInfoDiagnosticsWithFileName(dig *BuildInfoDiagnosticsOfFile) *DiagnosticsOrBuildInfoDiagnosticsWithFileName { + return &DiagnosticsOrBuildInfoDiagnosticsWithFileName{ buildInfoDiagnostics: t.toBuildInfoDiagnosticsWithFileName(dig.Diagnostics), } } @@ -135,10 +135,10 @@ func (t *toSnapshot) setChangeFileSet() { } func (t *toSnapshot) setSemanticDiagnostics() { - t.snapshot.fileInfos.Range(func(path tspath.Path, info *fileInfo) bool { + t.snapshot.fileInfos.Range(func(path tspath.Path, info *FileInfo) bool { // Initialize to have no diagnostics if its not changed file if !t.snapshot.changedFilesSet.Has(path) { - t.snapshot.semanticDiagnosticsPerFile.Store(path, &diagnosticsOrBuildInfoDiagnosticsWithFileName{}) + t.snapshot.semanticDiagnosticsPerFile.Store(path, &DiagnosticsOrBuildInfoDiagnosticsWithFileName{}) } return true }) diff --git a/internal/execute/incremental/emitfileshandler.go b/internal/execute/incremental/emitfileshandler.go index 4cde6a6df2..bb40199dc3 100644 --- a/internal/execute/incremental/emitfileshandler.go +++ b/internal/execute/incremental/emitfileshandler.go @@ -145,7 +145,7 @@ func (h *emitFilesHandler) emitFilesIncremental(options compiler.EmitOptions) [] } // Get updated errors that were not included in affected files emit - h.program.snapshot.emitDiagnosticsPerFile.Range(func(path tspath.Path, diagnostics *diagnosticsOrBuildInfoDiagnosticsWithFileName) bool { + h.program.snapshot.emitDiagnosticsPerFile.Range(func(path tspath.Path, diagnostics *DiagnosticsOrBuildInfoDiagnosticsWithFileName) bool { if _, ok := h.emitUpdates.Load(path); !ok { affectedFile := h.program.program.GetSourceFileByPath(path) if affectedFile == nil || !h.program.program.SourceFileMayBeEmitted(affectedFile, false) { @@ -299,7 +299,7 @@ func (h *emitFilesHandler) updateSnapshot() []*compiler.EmitResult { if update.result != nil { results = append(results, update.result) if len(update.result.Diagnostics) != 0 { - h.program.snapshot.emitDiagnosticsPerFile.Store(file.Path(), &diagnosticsOrBuildInfoDiagnosticsWithFileName{diagnostics: update.result.Diagnostics}) + h.program.snapshot.emitDiagnosticsPerFile.Store(file.Path(), &DiagnosticsOrBuildInfoDiagnosticsWithFileName{diagnostics: update.result.Diagnostics}) } } } diff --git a/internal/execute/incremental/program.go b/internal/execute/incremental/program.go index 3e2fd1eecd..ceac9c35d4 100644 --- a/internal/execute/incremental/program.go +++ b/internal/execute/incremental/program.go @@ -47,7 +47,7 @@ func NewProgram(program *compiler.Program, oldProgram *Program, host Host, testi if oldProgram != nil { incrementalProgram.testingData.OldProgramSemanticDiagnosticsPerFile = &oldProgram.snapshot.semanticDiagnosticsPerFile } else { - incrementalProgram.testingData.OldProgramSemanticDiagnosticsPerFile = &collections.SyncMap[tspath.Path, *diagnosticsOrBuildInfoDiagnosticsWithFileName]{} + incrementalProgram.testingData.OldProgramSemanticDiagnosticsPerFile = &collections.SyncMap[tspath.Path, *DiagnosticsOrBuildInfoDiagnosticsWithFileName]{} } incrementalProgram.testingData.UpdatedSignatureKinds = make(map[tspath.Path]SignatureUpdateKind) } @@ -55,8 +55,8 @@ func NewProgram(program *compiler.Program, oldProgram *Program, host Host, testi } type TestingData struct { - SemanticDiagnosticsPerFile *collections.SyncMap[tspath.Path, *diagnosticsOrBuildInfoDiagnosticsWithFileName] - OldProgramSemanticDiagnosticsPerFile *collections.SyncMap[tspath.Path, *diagnosticsOrBuildInfoDiagnosticsWithFileName] + SemanticDiagnosticsPerFile *collections.SyncMap[tspath.Path, *DiagnosticsOrBuildInfoDiagnosticsWithFileName] + OldProgramSemanticDiagnosticsPerFile *collections.SyncMap[tspath.Path, *DiagnosticsOrBuildInfoDiagnosticsWithFileName] UpdatedSignatureKinds map[tspath.Path]SignatureUpdateKind } @@ -240,7 +240,7 @@ func (p *Program) collectSemanticDiagnosticsOfAffectedFiles(ctx context.Context, // Commit changes to snapshot for file, diagnostics := range diagnosticsPerFile { - p.snapshot.semanticDiagnosticsPerFile.Store(file.Path(), &diagnosticsOrBuildInfoDiagnosticsWithFileName{diagnostics: diagnostics}) + p.snapshot.semanticDiagnosticsPerFile.Store(file.Path(), &DiagnosticsOrBuildInfoDiagnosticsWithFileName{diagnostics: diagnostics}) } if p.snapshot.semanticDiagnosticsPerFile.Size() == len(p.program.GetSourceFiles()) && p.snapshot.checkPending && !p.snapshot.options.NoCheck.IsTrue() { p.snapshot.checkPending = false diff --git a/internal/execute/incremental/programtosnapshot.go b/internal/execute/incremental/programtosnapshot.go index 7f380f39a8..dfaeb25131 100644 --- a/internal/execute/incremental/programtosnapshot.go +++ b/internal/execute/incremental/programtosnapshot.go @@ -140,7 +140,7 @@ func (t *toProgramSnapshot) computeProgramFileChanges() { t.snapshot.addFileToAffectedFilesPendingEmit(file.Path(), GetFileEmitKind(t.snapshot.options)) signature = version } - t.snapshot.fileInfos.Store(file.Path(), &fileInfo{ + t.snapshot.fileInfos.Store(file.Path(), &FileInfo{ version: version, signature: signature, affectsGlobalScope: affectsGlobalScope, @@ -154,7 +154,7 @@ func (t *toProgramSnapshot) computeProgramFileChanges() { func (t *toProgramSnapshot) handleFileDelete() { if t.oldProgram != nil { // If the global file is removed, add all files as changed - t.oldProgram.snapshot.fileInfos.Range(func(filePath tspath.Path, oldInfo *fileInfo) bool { + t.oldProgram.snapshot.fileInfos.Range(func(filePath tspath.Path, oldInfo *FileInfo) bool { if _, ok := t.snapshot.fileInfos.Load(filePath); !ok { if oldInfo.affectsGlobalScope { for _, file := range t.snapshot.getAllFilesExcludingDefaultLibraryFile(t.program, nil) { diff --git a/internal/execute/incremental/snapshot.go b/internal/execute/incremental/snapshot.go index d1ce2053cd..9ef4fdd0d8 100644 --- a/internal/execute/incremental/snapshot.go +++ b/internal/execute/incremental/snapshot.go @@ -16,17 +16,17 @@ import ( "github.com/zeebo/xxh3" ) -type fileInfo struct { +type FileInfo struct { version string signature string affectsGlobalScope bool impliedNodeFormat core.ResolutionMode } -func (f *fileInfo) Version() string { return f.version } -func (f *fileInfo) Signature() string { return f.signature } -func (f *fileInfo) AffectsGlobalScope() bool { return f.affectsGlobalScope } -func (f *fileInfo) ImpliedNodeFormat() core.ResolutionMode { return f.impliedNodeFormat } +func (f *FileInfo) Version() string { return f.version } +func (f *FileInfo) Signature() string { return f.signature } +func (f *FileInfo) AffectsGlobalScope() bool { return f.affectsGlobalScope } +func (f *FileInfo) ImpliedNodeFormat() core.ResolutionMode { return f.impliedNodeFormat } func ComputeHash(text string, hashWithText bool) string { hashBytes := xxh3.Hash128([]byte(text)).Bytes() @@ -145,7 +145,7 @@ type buildInfoDiagnosticWithFileName struct { skippedOnNoEmit bool } -type diagnosticsOrBuildInfoDiagnosticsWithFileName struct { +type DiagnosticsOrBuildInfoDiagnosticsWithFileName struct { diagnostics []*ast.Diagnostic buildInfoDiagnostics []*buildInfoDiagnosticWithFileName } @@ -179,7 +179,7 @@ func (b *buildInfoDiagnosticWithFileName) toDiagnostic(p *compiler.Program, file ) } -func (d *diagnosticsOrBuildInfoDiagnosticsWithFileName) getDiagnostics(p *compiler.Program, file *ast.SourceFile) []*ast.Diagnostic { +func (d *DiagnosticsOrBuildInfoDiagnosticsWithFileName) getDiagnostics(p *compiler.Program, file *ast.SourceFile) []*ast.Diagnostic { if d.diagnostics != nil { return d.diagnostics } @@ -194,14 +194,14 @@ type snapshot struct { // These are the fields that get serialized // Information of the file eg. its version, signature etc - fileInfos collections.SyncMap[tspath.Path, *fileInfo] + fileInfos collections.SyncMap[tspath.Path, *FileInfo] options *core.CompilerOptions // Contains the map of ReferencedSet=Referenced files of the file if module emit is enabled referencedMap referenceMap // Cache of semantic diagnostics for files with their Path being the key - semanticDiagnosticsPerFile collections.SyncMap[tspath.Path, *diagnosticsOrBuildInfoDiagnosticsWithFileName] + semanticDiagnosticsPerFile collections.SyncMap[tspath.Path, *DiagnosticsOrBuildInfoDiagnosticsWithFileName] // Cache of dts emit diagnostics for files with their Path being the key - emitDiagnosticsPerFile collections.SyncMap[tspath.Path, *diagnosticsOrBuildInfoDiagnosticsWithFileName] + emitDiagnosticsPerFile collections.SyncMap[tspath.Path, *DiagnosticsOrBuildInfoDiagnosticsWithFileName] // The map has key by source file's path that has been changed changedFilesSet collections.SyncSet[tspath.Path] // Files pending to be emitted diff --git a/internal/execute/incremental/snapshottobuildinfo.go b/internal/execute/incremental/snapshottobuildinfo.go index c700ccb330..57896db66d 100644 --- a/internal/execute/incremental/snapshottobuildinfo.go +++ b/internal/execute/incremental/snapshottobuildinfo.go @@ -164,7 +164,7 @@ func (t *toBuildInfo) toBuildInfoDiagnosticsFromDiagnostics(filePath tspath.Path }) } -func (t *toBuildInfo) toBuildInfoDiagnosticsOfFile(filePath tspath.Path, diags *diagnosticsOrBuildInfoDiagnosticsWithFileName) *BuildInfoDiagnosticsOfFile { +func (t *toBuildInfo) toBuildInfoDiagnosticsOfFile(filePath tspath.Path, diags *DiagnosticsOrBuildInfoDiagnosticsWithFileName) *BuildInfoDiagnosticsOfFile { if len(diags.diagnostics) > 0 { return &BuildInfoDiagnosticsOfFile{ FileId: t.toFileId(filePath), diff --git a/internal/execute/tsctests/runner.go b/internal/execute/tsctests/runner.go index 7cb8c261bd..319e724ed9 100644 --- a/internal/execute/tsctests/runner.go +++ b/internal/execute/tsctests/runner.go @@ -17,7 +17,7 @@ import ( type tscEdit struct { caption string commandLineArgs []string - edit func(*testSys) + edit func(*TestSys) expectedDiff string } @@ -40,7 +40,7 @@ type tscInput struct { windowsStyleRoot string } -func (test *tscInput) executeCommand(sys *testSys, baselineBuilder *strings.Builder, commandLineArgs []string) tsc.CommandLineResult { +func (test *tscInput) executeCommand(sys *TestSys, baselineBuilder *strings.Builder, commandLineArgs []string) tsc.CommandLineResult { fmt.Fprint(baselineBuilder, "tsgo ", strings.Join(commandLineArgs, " "), "\n") result := execute.CommandLine(sys, commandLineArgs, sys) switch result.Status { @@ -85,7 +85,7 @@ func (test *tscInput) run(t *testing.T, scenario string) { for index, do := range test.edits { sys.clearOutput() wg := core.NewWorkGroup(false) - var nonIncrementalSys *testSys + var nonIncrementalSys *TestSys commandLineArgs := core.IfElse(do.commandLineArgs == nil, test.commandLineArgs, do.commandLineArgs) wg.Queue(func() { baselineBuilder.WriteString(fmt.Sprintf("\n\nEdit [%d]:: %s\n", index, do.caption)) @@ -133,7 +133,7 @@ func (test *tscInput) run(t *testing.T, scenario string) { }) } -func getDiffForIncremental(incrementalSys *testSys, nonIncrementalSys *testSys) string { +func getDiffForIncremental(incrementalSys *TestSys, nonIncrementalSys *TestSys) string { var diffBuilder strings.Builder nonIncrementalOutputs := nonIncrementalSys.fs.writtenFiles.ToSlice() diff --git a/internal/execute/tsctests/sys.go b/internal/execute/tsctests/sys.go index 199fce8e76..a11f33865e 100644 --- a/internal/execute/tsctests/sys.go +++ b/internal/execute/tsctests/sys.go @@ -84,9 +84,9 @@ func (t *TestClock) SinceStart() time.Duration { return t.Now().Sub(t.start) } -func NewTscSystem(files FileMap, useCaseSensitiveFileNames bool, cwd string) *testSys { +func NewTscSystem(files FileMap, useCaseSensitiveFileNames bool, cwd string) *TestSys { clock := &TestClock{start: time.Now()} - return &testSys{ + return &TestSys{ fs: &testFs{ FS: vfstest.FromMapWithClock(files, useCaseSensitiveFileNames, clock), }, @@ -95,7 +95,7 @@ func NewTscSystem(files FileMap, useCaseSensitiveFileNames bool, cwd string) *te } } -func newTestSys(tscInput *tscInput, forIncrementalCorrectness bool) *testSys { +func newTestSys(tscInput *tscInput, forIncrementalCorrectness bool) *TestSys { cwd := tscInput.cwd if cwd == "" { cwd = "/home/src/workspaces/project" @@ -138,7 +138,7 @@ type snapshot struct { defaultLibs *collections.SyncSet[string] } -type testSys struct { +type TestSys struct { currentWrite *strings.Builder programBaselines strings.Builder programIncludeBaselines strings.Builder @@ -154,31 +154,31 @@ type testSys struct { } var ( - _ tsc.System = (*testSys)(nil) - _ tsc.CommandLineTesting = (*testSys)(nil) + _ tsc.System = (*TestSys)(nil) + _ tsc.CommandLineTesting = (*TestSys)(nil) ) -func (s *testSys) Now() time.Time { +func (s *TestSys) Now() time.Time { return s.clock.Now() } -func (s *testSys) SinceStart() time.Duration { +func (s *TestSys) SinceStart() time.Duration { return s.clock.SinceStart() } -func (s *testSys) FS() vfs.FS { +func (s *TestSys) FS() vfs.FS { return s.fs } -func (s *testSys) fsFromFileMap() iovfs.FsWithSys { +func (s *TestSys) fsFromFileMap() iovfs.FsWithSys { return s.fs.FS.(iovfs.FsWithSys) } -func (s *testSys) mapFs() *vfstest.MapFS { +func (s *TestSys) mapFs() *vfstest.MapFS { return s.fsFromFileMap().FSys().(*vfstest.MapFS) } -func (s *testSys) ensureLibPathExists(path string) { +func (s *TestSys) ensureLibPathExists(path string) { path = s.defaultLibraryPath + "/" + path if _, ok := s.fsFromFileMap().ReadFile(path); !ok { if s.fs.defaultLibs == nil { @@ -192,34 +192,34 @@ func (s *testSys) ensureLibPathExists(path string) { } } -func (s *testSys) DefaultLibraryPath() string { +func (s *TestSys) DefaultLibraryPath() string { return s.defaultLibraryPath } -func (s *testSys) GetCurrentDirectory() string { +func (s *TestSys) GetCurrentDirectory() string { return s.cwd } -func (s *testSys) Writer() io.Writer { +func (s *TestSys) Writer() io.Writer { return s.currentWrite } -func (s *testSys) WriteOutputIsTTY() bool { +func (s *TestSys) WriteOutputIsTTY() bool { return true } -func (s *testSys) GetWidthOfTerminal() int { +func (s *TestSys) GetWidthOfTerminal() int { if widthStr := s.GetEnvironmentVariable("TS_TEST_TERMINAL_WIDTH"); widthStr != "" { return core.Must(strconv.Atoi(widthStr)) } return 0 } -func (s *testSys) GetEnvironmentVariable(name string) string { +func (s *TestSys) GetEnvironmentVariable(name string) string { return s.env[name] } -func (s *testSys) OnEmittedFiles(result *compiler.EmitResult, mTimesCache *collections.SyncMap[tspath.Path, time.Time]) { +func (s *TestSys) OnEmittedFiles(result *compiler.EmitResult, mTimesCache *collections.SyncMap[tspath.Path, time.Time]) { if result != nil { for _, file := range result.EmittedFiles { modTime := s.mapFs().GetModTime(file) @@ -246,39 +246,39 @@ func (s *testSys) OnEmittedFiles(result *compiler.EmitResult, mTimesCache *colle } } -func (s *testSys) OnListFilesStart(w io.Writer) { +func (s *TestSys) OnListFilesStart(w io.Writer) { fmt.Fprintln(w, listFileStart) } -func (s *testSys) OnListFilesEnd(w io.Writer) { +func (s *TestSys) OnListFilesEnd(w io.Writer) { fmt.Fprintln(w, listFileEnd) } -func (s *testSys) OnStatisticsStart(w io.Writer) { +func (s *TestSys) OnStatisticsStart(w io.Writer) { fmt.Fprintln(w, statisticsStart) } -func (s *testSys) OnStatisticsEnd(w io.Writer) { +func (s *TestSys) OnStatisticsEnd(w io.Writer) { fmt.Fprintln(w, statisticsEnd) } -func (s *testSys) OnBuildStatusReportStart(w io.Writer) { +func (s *TestSys) OnBuildStatusReportStart(w io.Writer) { fmt.Fprintln(w, buildStatusReportStart) } -func (s *testSys) OnBuildStatusReportEnd(w io.Writer) { +func (s *TestSys) OnBuildStatusReportEnd(w io.Writer) { fmt.Fprintln(w, buildStatusReportEnd) } -func (s *testSys) OnWatchStatusReportStart() { +func (s *TestSys) OnWatchStatusReportStart() { fmt.Fprintln(s.Writer(), watchStatusReportStart) } -func (s *testSys) OnWatchStatusReportEnd() { +func (s *TestSys) OnWatchStatusReportEnd() { fmt.Fprintln(s.Writer(), watchStatusReportEnd) } -func (s *testSys) GetTrace(w io.Writer) func(str string) { +func (s *TestSys) GetTrace(w io.Writer) func(str string) { return func(str string) { fmt.Fprintln(w, traceStart) defer fmt.Fprintln(w, traceEnd) @@ -288,7 +288,7 @@ func (s *testSys) GetTrace(w io.Writer) func(str string) { } } -func (s *testSys) writeHeaderToBaseline(builder *strings.Builder, program *incremental.Program) { +func (s *TestSys) writeHeaderToBaseline(builder *strings.Builder, program *incremental.Program) { if builder.Len() != 0 { builder.WriteString("\n") } @@ -301,7 +301,7 @@ func (s *testSys) writeHeaderToBaseline(builder *strings.Builder, program *incre } } -func (s *testSys) OnProgram(program *incremental.Program) { +func (s *TestSys) OnProgram(program *incremental.Program) { s.writeHeaderToBaseline(&s.programBaselines, program) testingData := program.GetTestingData() @@ -357,7 +357,7 @@ func (s *testSys) OnProgram(program *incremental.Program) { } } -func (s *testSys) baselinePrograms(baseline *strings.Builder, header string) string { +func (s *TestSys) baselinePrograms(baseline *strings.Builder, header string) string { baseline.WriteString(s.programBaselines.String()) s.programBaselines.Reset() var result string @@ -370,7 +370,7 @@ func (s *testSys) baselinePrograms(baseline *strings.Builder, header string) str return result } -func (s *testSys) serializeState(baseline *strings.Builder) { +func (s *TestSys) serializeState(baseline *strings.Builder) { s.baselineOutput(baseline) s.baselineFSwithDiff(baseline) // todo watch @@ -399,7 +399,7 @@ var ( traceEnd = "!!! Trace end" ) -func (s *testSys) baselineOutput(baseline io.Writer) { +func (s *TestSys) baselineOutput(baseline io.Writer) { fmt.Fprint(baseline, "\nOutput::\n") output := s.getOutput(false) fmt.Fprint(baseline, output) @@ -484,7 +484,7 @@ func (o *outputSanitizer) addOrSkipLinesForComparing( panic("Expected lineEnd" + lineEnd + " not found after " + lineStart) } -func (s *testSys) getOutput(forComparing bool) string { +func (s *TestSys) getOutput(forComparing bool) string { lines := strings.Split(s.currentWrite.String(), "\n") transformer := &outputSanitizer{ forComparing: forComparing, @@ -494,12 +494,12 @@ func (s *testSys) getOutput(forComparing bool) string { return transformer.transformLines() } -func (s *testSys) clearOutput() { +func (s *TestSys) clearOutput() { s.currentWrite.Reset() s.tracer.Reset() } -func (s *testSys) baselineFSwithDiff(baseline io.Writer) { +func (s *TestSys) baselineFSwithDiff(baseline io.Writer) { // todo: baselines the entire fs, possibly doesn't correctly diff all cases of emitted files, since emit isn't fully implemented and doesn't always emit the same way as strada snap := map[string]*diffEntry{} @@ -549,7 +549,7 @@ func (s *testSys) baselineFSwithDiff(baseline io.Writer) { s.fs.writtenFiles = collections.SyncSet[string]{} // Reset written files after baseline } -func (s *testSys) addFsEntryDiff(diffs map[string]string, newDirContent *diffEntry, path string) { +func (s *TestSys) addFsEntryDiff(diffs map[string]string, newDirContent *diffEntry, path string) { var oldDirContent *diffEntry var defaultLibs *collections.SyncSet[string] if s.serializedDiff != nil { @@ -579,19 +579,19 @@ func (s *testSys) addFsEntryDiff(diffs map[string]string, newDirContent *diffEnt } } -func (s *testSys) writeFileNoError(path string, content string, writeByteOrderMark bool) { +func (s *TestSys) writeFileNoError(path string, content string, writeByteOrderMark bool) { if err := s.fsFromFileMap().WriteFile(path, content, writeByteOrderMark); err != nil { panic(err) } } -func (s *testSys) removeNoError(path string) { +func (s *TestSys) removeNoError(path string) { if err := s.fsFromFileMap().Remove(path); err != nil { panic(err) } } -func (s *testSys) readFileNoError(path string) string { +func (s *TestSys) readFileNoError(path string) string { content, ok := s.fsFromFileMap().ReadFile(path) if !ok { panic("File not found: " + path) @@ -599,29 +599,29 @@ func (s *testSys) readFileNoError(path string) string { return content } -func (s *testSys) renameFileNoError(oldPath string, newPath string) { +func (s *TestSys) renameFileNoError(oldPath string, newPath string) { s.writeFileNoError(newPath, s.readFileNoError(oldPath), false) s.removeNoError(oldPath) } -func (s *testSys) replaceFileText(path string, oldText string, newText string) { +func (s *TestSys) replaceFileText(path string, oldText string, newText string) { content := s.readFileNoError(path) content = strings.Replace(content, oldText, newText, 1) s.writeFileNoError(path, content, false) } -func (s *testSys) replaceFileTextAll(path string, oldText string, newText string) { +func (s *TestSys) replaceFileTextAll(path string, oldText string, newText string) { content := s.readFileNoError(path) content = strings.ReplaceAll(content, oldText, newText) s.writeFileNoError(path, content, false) } -func (s *testSys) appendFile(path string, text string) { +func (s *TestSys) appendFile(path string, text string) { content := s.readFileNoError(path) s.writeFileNoError(path, content+text, false) } -func (s *testSys) prependFile(path string, text string) { +func (s *TestSys) prependFile(path string, text string) { content := s.readFileNoError(path) s.writeFileNoError(path, text+content, false) } diff --git a/internal/execute/tsctests/tsc_test.go b/internal/execute/tsctests/tsc_test.go index 31f0f94911..df7e4e39b1 100644 --- a/internal/execute/tsctests/tsc_test.go +++ b/internal/execute/tsctests/tsc_test.go @@ -251,7 +251,7 @@ func TestTscComposite(t *testing.T) { edits: []*tscEdit{ { caption: "convert to modules", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/tsconfig.json", "none", "es2015") }, }, @@ -895,7 +895,7 @@ func TestTscExtends(t *testing.T) { getTscExtendsConfigDirTestCase("", []string{"--b", "-w", "--explainFiles", "--v"}, []*tscEdit{ { caption: "edit extended config file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError( "/home/src/projects/configs/first/tsconfig.json", stringtestutil.Dedent(` @@ -945,25 +945,25 @@ func TestTscIncremental(t *testing.T) { edits: []*tscEdit{ { caption: "change enum value", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText(changeEnumFile, "1", "2") }, }, { caption: "change enum value again", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText(changeEnumFile, "2", "3") }, }, { caption: "something else changes in b.d.ts", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/home/src/workspaces/project/b.d.ts", "export const randomThing = 10;") }, }, { caption: "something else changes in b.d.ts again", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/home/src/workspaces/project/b.d.ts", "export const randomThing2 = 10;") }, }, @@ -1048,14 +1048,14 @@ func TestTscIncremental(t *testing.T) { noChange, { caption: "modify public to protected", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/MessageablePerson.ts", "public", "protected") }, }, noChange, { caption: "modify protected to public", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/MessageablePerson.ts", "protected", "public") }, }, @@ -1094,14 +1094,14 @@ func TestTscIncremental(t *testing.T) { noChange, { caption: "modify public to protected", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/MessageablePerson.ts", "public", "protected") }, }, noChange, { caption: "modify protected to public", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/MessageablePerson.ts", "protected", "public") }, }, @@ -1153,7 +1153,7 @@ func TestTscIncremental(t *testing.T) { noChange, { caption: "modify d.ts file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/home/src/workspaces/project/src/main.d.ts", "export const xy = 100;") }, }, @@ -1185,7 +1185,7 @@ func TestTscIncremental(t *testing.T) { edits: []*tscEdit{ { caption: "tsbuildinfo written has error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.prependFile("/home/src/workspaces/project/tsconfig.tsbuildinfo", "Some random string") }, }, @@ -1216,19 +1216,19 @@ func TestTscIncremental(t *testing.T) { noChange, { caption: "Modify main file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile(`/home/src/workspaces/project/src/main.ts`, `something();`) }, }, { caption: "Modify main file again", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile(`/home/src/workspaces/project/src/main.ts`, `something();`) }, }, { caption: "Add new file and update main file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError(`/home/src/workspaces/project/src/newFile.ts`, "function foo() { return 20; }", false) sys.prependFile( `/home/src/workspaces/project/src/main.ts`, @@ -1240,13 +1240,13 @@ func TestTscIncremental(t *testing.T) { }, { caption: "Write file that could not be resolved", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError(`/home/src/workspaces/project/src/fileNotFound.ts`, "function something2() { return 20; }", false) }, }, { caption: "Modify main file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile(`/home/src/workspaces/project/src/main.ts`, `something();`) }, }, @@ -1327,7 +1327,7 @@ func TestTscIncremental(t *testing.T) { edits: []*tscEdit{ { caption: "Modify imports used in global file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/home/src/workspaces/project/constants.ts", "export default 2;", false) }, expectedDiff: "Currently there is issue with d.ts emit for export default = 1 to widen in dts which is why we are not re-computing errors and results in incorrect error reporting", @@ -1353,7 +1353,7 @@ func TestTscIncremental(t *testing.T) { edits: []*tscEdit{ { caption: "Modify imports used in global file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/home/src/workspaces/project/constants.ts", "export default 2;", false) }, expectedDiff: "Currently there is issue with d.ts emit for export default = 1 to widen in dts which is why we are not re-computing errors and results in incorrect error reporting", @@ -1376,7 +1376,7 @@ func TestTscIncremental(t *testing.T) { edits: []*tscEdit{ { caption: "delete file with imports", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.removeNoError("/home/src/workspaces/project/file2.ts") }, }, @@ -1428,7 +1428,7 @@ func TestTscIncremental(t *testing.T) { edits: []*tscEdit{ { caption: "modify js file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/home/src/workspaces/project/src/bug.js", `export const something = 1;`) }, }, @@ -1495,7 +1495,7 @@ func TestTscIncremental(t *testing.T) { noChange, { caption: "local change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/a.ts", "Local = 1", "Local = 10") }, }, @@ -1517,7 +1517,7 @@ func TestTscIncremental(t *testing.T) { }, { caption: "declarationMap enabling", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/tsconfig.json", `"composite": true,`, `"composite": true, "declarationMap": true`) }, }, @@ -1566,7 +1566,7 @@ func TestTscIncremental(t *testing.T) { }, { caption: "local change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/a.ts", "Local = 1", "Local = 10") }, }, @@ -2239,7 +2239,7 @@ func TestTscModuleResolution(t *testing.T) { edits: []*tscEdit{ { caption: "Delete package.json", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.removeNoError("/home/src/workspaces/project/package.json") }, // !!! repopulateInfo on diagnostics not yet implemented @@ -2291,7 +2291,7 @@ func TestTscModuleResolution(t *testing.T) { edits: []*tscEdit{ { caption: "delete the alternateResult in @types", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.removeNoError("/home/src/projects/project/node_modules/@types/bar/index.d.ts") }, // !!! repopulateInfo on diagnostics not yet implemented @@ -2299,7 +2299,7 @@ func TestTscModuleResolution(t *testing.T) { }, { caption: "delete the node10Result in package/types", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.removeNoError("/home/src/projects/project/node_modules/foo/index.d.ts") }, // !!! repopulateInfo on diagnostics not yet implemented @@ -2307,7 +2307,7 @@ func TestTscModuleResolution(t *testing.T) { }, { caption: "add the alternateResult in @types", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/home/src/projects/project/node_modules/@types/bar/index.d.ts", getTscModuleResolutionAlternateResultDts("bar"), false) }, // !!! repopulateInfo on diagnostics not yet implemented @@ -2315,37 +2315,37 @@ func TestTscModuleResolution(t *testing.T) { }, { caption: "add the alternateResult in package/types", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/home/src/projects/project/node_modules/foo/index.d.ts", getTscModuleResolutionAlternateResultDts("foo"), false) }, }, { caption: "update package.json from @types so error is fixed", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/home/src/projects/project/node_modules/@types/bar/package.json", getTscModuleResolutionAlternateResultAtTypesPackageJson("bar" /*addTypesCondition*/, true), false) }, }, { caption: "update package.json so error is fixed", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/home/src/projects/project/node_modules/foo/package.json", getTscModuleResolutionAlternateResultPackageJson("foo" /*addTypes*/, true /*addTypesCondition*/, true), false) }, }, { caption: "update package.json from @types so error is introduced", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/home/src/projects/project/node_modules/@types/bar2/package.json", getTscModuleResolutionAlternateResultAtTypesPackageJson("bar2" /*addTypesCondition*/, false), false) }, }, { caption: "update package.json so error is introduced", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/home/src/projects/project/node_modules/foo2/package.json", getTscModuleResolutionAlternateResultPackageJson("foo2" /*addTypes*/, true /*addTypesCondition*/, false), false) }, }, { caption: "delete the alternateResult in @types", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.removeNoError("/home/src/projects/project/node_modules/@types/bar2/index.d.ts") }, // !!! repopulateInfo on diagnostics not yet implemented @@ -2353,7 +2353,7 @@ func TestTscModuleResolution(t *testing.T) { }, { caption: "delete the node10Result in package/types", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.removeNoError("/home/src/projects/project/node_modules/foo2/index.d.ts") }, // !!! repopulateInfo on diagnostics not yet implemented @@ -2361,7 +2361,7 @@ func TestTscModuleResolution(t *testing.T) { }, { caption: "add the alternateResult in @types", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/home/src/projects/project/node_modules/@types/bar2/index.d.ts", getTscModuleResolutionAlternateResultDts("bar2"), false) }, // !!! repopulateInfo on diagnostics not yet implemented @@ -2369,7 +2369,7 @@ func TestTscModuleResolution(t *testing.T) { }, { caption: "add the ndoe10Result in package/types", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/home/src/projects/project/node_modules/foo2/index.d.ts", getTscModuleResolutionAlternateResultDts("foo2"), false) }, }, @@ -2416,7 +2416,7 @@ func TestTscModuleResolution(t *testing.T) { edits: []*tscEdit{ { caption: "Append text", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile(`/user/username/projects/myproject/project1/index.ts`, "const bar = 10;") }, }, @@ -2468,27 +2468,27 @@ func TestTscModuleResolution(t *testing.T) { edits: []*tscEdit{ { caption: "reports import errors after change to package file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText(`/user/username/projects/myproject/packages/pkg1/package.json`, `"module"`, `"commonjs"`) }, expectedDiff: "Package.json watch pending, so no change detected yet", }, { caption: "removes those errors when a package file is changed back", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText(`/user/username/projects/myproject/packages/pkg1/package.json`, `"commonjs"`, `"module"`) }, }, { caption: "reports import errors after change to package file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText(`/user/username/projects/myproject/packages/pkg1/package.json`, `"module"`, `"commonjs"`) }, expectedDiff: "Package.json watch pending, so no change detected yet", }, { caption: "removes those errors when a package file is changed to cjs extensions", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText(`/user/username/projects/myproject/packages/pkg2/package.json`, `"build/index.js"`, `"build/index.cjs"`) sys.renameFileNoError(`/user/username/projects/myproject/packages/pkg2/index.ts`, `/user/username/projects/myproject/packages/pkg2/index.cts`) }, @@ -2537,14 +2537,14 @@ func TestTscModuleResolution(t *testing.T) { edits: []*tscEdit{ { caption: "reports import errors after change to package file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText(`/user/username/projects/myproject/packages/pkg2/package.json`, `index.js`, `other.js`) }, expectedDiff: "Package.json watch pending, so no change detected yet", }, { caption: "removes those errors when a package file is changed back", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText(`/user/username/projects/myproject/packages/pkg2/package.json`, `other.js`, `index.js`) }, }, @@ -2626,13 +2626,13 @@ func TestTscNoCheck(t *testing.T) { } fixErrorNoCheck := &tscEdit{ caption: "Fix `a` error with noCheck", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/home/src/workspaces/project/a.ts", `export const a = "hello";`, false) }, } addErrorNoCheck := &tscEdit{ caption: "Introduce error with noCheck", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/home/src/workspaces/project/a.ts", scenario.aText, false) }, } @@ -2664,7 +2664,7 @@ func TestTscNoCheck(t *testing.T) { noChangeWithCheck, // Should check errors and update buildInfo { caption: "Add file with error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/home/src/workspaces/project/c.ts", `export const c: number = "hello";`, false) }, commandLineArgs: commandLineArgs, @@ -2787,7 +2787,7 @@ func TestTscNoEmit(t *testing.T) { noChange, { caption: "Fix error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/home/src/projects/project/a.ts", fixedATsContent, false) }, }, @@ -2799,7 +2799,7 @@ func TestTscNoEmit(t *testing.T) { noChange, { caption: "Introduce error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/home/src/projects/project/a.ts", scenario.aText, false) }, }, @@ -2824,37 +2824,37 @@ func TestTscNoEmit(t *testing.T) { return []*tscEdit{ { caption: "Fix error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/home/src/projects/project/a.ts", fixedATsContent, false) }, }, { caption: "Emit after fixing error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/projects/project/tsconfig.json", `"noEmit": true`, `"noEmit": false`) }, }, { caption: "no Emit run after fixing error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/projects/project/tsconfig.json", `"noEmit": false`, `"noEmit": true`) }, }, { caption: "Introduce error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/home/src/projects/project/a.ts", scenario.aText, false) }, }, { caption: "Emit when error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/projects/project/tsconfig.json", `"noEmit": true`, `"noEmit": false`) }, }, { caption: "no Emit run when error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/projects/project/tsconfig.json", `"noEmit": false`, `"noEmit": true`) }, }, @@ -2920,10 +2920,10 @@ func TestTscNoEmit(t *testing.T) { caption: "No Change run with emit", commandLineArgs: commandLineArgs, } - introduceError := func(sys *testSys) { + introduceError := func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/src/class.ts", "prop", "prop1") } - fixError := func(sys *testSys) { + fixError := func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/src/class.ts", "prop1", "prop") } testCases := make([]*tscInput, 0, len(noEmitChangesScenarios)) @@ -3025,7 +3025,7 @@ func TestTscNoEmit(t *testing.T) { }, { caption: "Fix the error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/projects/project/a.ts", "private", "public") }, }, @@ -3089,7 +3089,7 @@ func TestTscNoEmit(t *testing.T) { []*tscEdit{ { caption: "Fix the another ", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/projects/project/c.ts", "private", "public") }, commandLineArgs: slices.Concat(commandLineArgs, []string{"--noEmit", "--declaration", "--declarationMap"}), @@ -3118,13 +3118,13 @@ func TestTscNoEmit(t *testing.T) { edits: []*tscEdit{ { caption: "No change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError(`/user/username/projects/myproject/a.js`, sys.readFileNoError(`/user/username/projects/myproject/a.js`), false) }, }, { caption: "change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError(`/user/username/projects/myproject/a.js`, "const x = 10;", false) }, }, @@ -3203,7 +3203,7 @@ func TestTscNoEmitOnError(t *testing.T) { noChange, { caption: "Fix error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/user/username/projects/noEmitOnError/src/main.ts", scenario.fixedErrorContent, false) }, }, @@ -3249,7 +3249,7 @@ func TestTscNoEmitOnError(t *testing.T) { if edits != nil { edits = append(edits, &tscEdit{ caption: scenario.subScenario, - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError(`/user/username/projects/noEmitOnError/src/main.ts`, scenario.mainErrorContent, false) }, }) @@ -3257,19 +3257,19 @@ func TestTscNoEmitOnError(t *testing.T) { edits = append(edits, &tscEdit{ caption: "No Change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError(`/user/username/projects/noEmitOnError/src/main.ts`, sys.readFileNoError(`/user/username/projects/noEmitOnError/src/main.ts`), false) }, }, &tscEdit{ caption: "Fix " + scenario.subScenario, - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/user/username/projects/noEmitOnError/src/main.ts", scenario.fixedErrorContent, false) }, }, &tscEdit{ caption: "No Change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError(`/user/username/projects/noEmitOnError/src/main.ts`, sys.readFileNoError(`/user/username/projects/noEmitOnError/src/main.ts`), false) }, }, @@ -3363,14 +3363,14 @@ func TestTscNoEmitOnError(t *testing.T) { edits: []*tscEdit{ { caption: "error and enable declarationMap", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/a.ts", "x", "x: 20") }, commandLineArgs: []string{"--declarationMap"}, }, { caption: "fix error declarationMap", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/a.ts", "x: 20", "x") }, commandLineArgs: []string{"--declarationMap"}, @@ -3394,7 +3394,7 @@ func TestTscNoEmitOnError(t *testing.T) { edits: []*tscEdit{ { caption: "delete file without error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.removeNoError("/home/src/workspaces/project/file2.ts") }, }, diff --git a/internal/execute/tsctests/tscbuild_test.go b/internal/execute/tsctests/tscbuild_test.go index 5c7a91b293..b1e709cacf 100644 --- a/internal/execute/tsctests/tscbuild_test.go +++ b/internal/execute/tsctests/tscbuild_test.go @@ -65,13 +65,13 @@ func TestBuildCommandLine(t *testing.T) { noChange, { caption: "local change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/home/src/workspaces/solution/project1/src/a.ts", "const aa = 10;") }, }, { caption: "non local change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/home/src/workspaces/solution/project1/src/a.ts", "export const aaa = 10;") }, }, @@ -82,26 +82,26 @@ func TestBuildCommandLine(t *testing.T) { noChange, { caption: "js emit with change without emitDeclarationOnly", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/home/src/workspaces/solution/project1/src/b.ts", "const alocal = 10;") }, commandLineArgs: []string{"--b", "project2/src", "--verbose"}, }, { caption: "local change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/home/src/workspaces/solution/project1/src/b.ts", "const aaaa = 10;") }, }, { caption: "non local change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/home/src/workspaces/solution/project1/src/b.ts", "export const aaaaa = 10;") }, }, { caption: "js emit with change without emitDeclarationOnly", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/home/src/workspaces/solution/project1/src/b.ts", "export const a2 = 10;") }, commandLineArgs: []string{"--b", "project2/src", "--verbose"}, @@ -117,7 +117,7 @@ func TestBuildCommandLine(t *testing.T) { noChange, { caption: "change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/home/src/workspaces/solution/project1/src/a.ts", "const aa = 10;") }, }, @@ -132,7 +132,7 @@ func TestBuildCommandLine(t *testing.T) { }, { caption: "js emit with change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/home/src/workspaces/solution/project1/src/b.ts", "const blocal = 10;") }, commandLineArgs: []string{"--b", "project2/src", "--verbose", "--emitDeclarationOnly", "false"}, @@ -179,7 +179,7 @@ func TestBuildCommandLine(t *testing.T) { noChange, { caption: "local change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/a.ts", "Local = 1", "Local = 10") }, }, @@ -220,7 +220,7 @@ func TestBuildCommandLine(t *testing.T) { noChange, { caption: "local change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/a.ts", "Local = 1", "Local = 10") }, }, @@ -357,20 +357,20 @@ func TestBuildConfigFileErrors(t *testing.T) { edits: []*tscEdit{ { caption: "reports syntax errors after change to config file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/tsconfig.json", ",", `, "declaration": true`) }, }, { caption: "reports syntax errors after change to ts file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/home/src/workspaces/project/a.ts", "export function fooBar() { }") }, }, noChange, { caption: "builds after fixing config file errors", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/home/src/workspaces/project/tsconfig.json", stringtestutil.Dedent(` { "compilerOptions": { @@ -410,25 +410,25 @@ func TestBuildConfigFileErrors(t *testing.T) { edits: []*tscEdit{ { caption: "reports syntax errors after change to config file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/tsconfig.json", ",", `, "declaration": true`) }, }, { caption: "reports syntax errors after change to ts file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/home/src/workspaces/project/a.ts", "export function fooBar() { }") }, }, { caption: "reports error when there is no change to tsconfig file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/tsconfig.json", "", "") }, }, { caption: "builds after fixing config file errors", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/home/src/workspaces/project/tsconfig.json", stringtestutil.Dedent(` { "compilerOptions": { @@ -698,7 +698,7 @@ func TestBuildDemoProject(t *testing.T) { edits: []*tscEdit{ { caption: "Fix error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/user/username/projects/demo/core/tsconfig.json", stringtestutil.Dedent(` { "extends": "../tsconfig-base.json", @@ -724,7 +724,7 @@ func TestBuildDemoProject(t *testing.T) { edits: []*tscEdit{ { caption: "Prepend a line", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.prependFile("/user/username/projects/demo/core/utilities.ts", "\n") }, }, @@ -806,7 +806,7 @@ func TestBuildEmitDeclarationOnly(t *testing.T) { edits: []*tscEdit{ { caption: "incremental-declaration-changes", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/src/a.ts", "b: B;", "b: B; foo: any;") }, }, @@ -823,7 +823,7 @@ func TestBuildEmitDeclarationOnly(t *testing.T) { edits: []*tscEdit{ { caption: "incremental-declaration-doesnt-change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText( "/home/src/workspaces/project/src/a.ts", "export interface A {", @@ -835,7 +835,7 @@ func TestBuildEmitDeclarationOnly(t *testing.T) { }, { caption: "incremental-declaration-changes", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/src/a.ts", "b: B;", "b: B; foo: any;") }, }, @@ -887,7 +887,7 @@ func TestBuildFileDelete(t *testing.T) { edits: []*tscEdit{ { caption: "delete child2 file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.removeNoError("/home/src/workspaces/solution/child/child2.ts") sys.removeNoError("/home/src/workspaces/solution/child/child2.js") sys.removeNoError("/home/src/workspaces/solution/child/child2.d.ts") @@ -919,7 +919,7 @@ func TestBuildFileDelete(t *testing.T) { edits: []*tscEdit{ { caption: "delete child2 file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.removeNoError("/home/src/workspaces/solution/child/child2.ts") sys.removeNoError("/home/src/workspaces/solution/child/child2.js") }, @@ -999,13 +999,13 @@ func TestBuildInferredTypeFromTransitiveModule(t *testing.T) { edits: []*tscEdit{ { caption: "incremental-declaration-changes", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/bar.ts", "param: string", "") }, }, { caption: "incremental-declaration-changes", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/bar.ts", "foobar()", "foobar(param: string)") }, }, @@ -1018,13 +1018,13 @@ func TestBuildInferredTypeFromTransitiveModule(t *testing.T) { edits: []*tscEdit{ { caption: "incremental-declaration-changes", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/bar.ts", "param: string", "") }, }, { caption: "incremental-declaration-changes", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/bar.ts", "foobar()", "foobar(param: string)") }, }, @@ -1040,25 +1040,25 @@ func TestBuildInferredTypeFromTransitiveModule(t *testing.T) { edits: []*tscEdit{ { caption: "incremental-declaration-changes", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/bar.ts", "param: string", "") }, }, { caption: "incremental-declaration-changes", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/bar.ts", "foobar()", "foobar(param: string)") }, }, { caption: "incremental-declaration-changes", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/bar.ts", "param: string", "") }, }, { caption: "Fix Error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/lazyIndex.ts", `bar("hello")`, "bar()") }, }, @@ -1295,13 +1295,13 @@ func TestBuildLateBoundSymbol(t *testing.T) { edits: []*tscEdit{ { caption: "incremental-declaration-doesnt-change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/project/src/main.ts", "const x = 10;", "") }, }, { caption: "incremental-declaration-doesnt-change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/home/src/workspaces/project/src/main.ts", "const x = 10;") }, }, @@ -1675,14 +1675,14 @@ func TestBuildProgramUpdates(t *testing.T) { { caption: "Introduce error", // Change message in library to message2 - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileTextAll("/user/username/projects/sample1/Library/library.ts", "message", "message2") }, }, { caption: "Fix error", // Revert library changes - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileTextAll("/user/username/projects/sample1/Library/library.ts", "message2", "message") }, }, @@ -1710,7 +1710,7 @@ func TestBuildProgramUpdates(t *testing.T) { edits: []*tscEdit{ { caption: "Fix error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/user/username/projects/solution/app/fileWithError.ts", "private p = 12", "") }, }, @@ -1738,7 +1738,7 @@ func TestBuildProgramUpdates(t *testing.T) { edits: []*tscEdit{ { caption: "Change fileWithoutError", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileTextAll("/user/username/projects/solution/app/fileWithoutError.ts", "myClass", "myClass2") }, }, @@ -1766,7 +1766,7 @@ func TestBuildProgramUpdates(t *testing.T) { edits: []*tscEdit{ { caption: "Introduce error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/user/username/projects/solution/app/fileWithError.ts", stringtestutil.Dedent(` export var myClassWithError = class { tags() { } @@ -1777,7 +1777,7 @@ func TestBuildProgramUpdates(t *testing.T) { }, { caption: "Fix error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/user/username/projects/solution/app/fileWithError.ts", "private p = 12", "") }, }, @@ -1805,7 +1805,7 @@ func TestBuildProgramUpdates(t *testing.T) { edits: []*tscEdit{ { caption: "Introduce error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/user/username/projects/solution/app/fileWithError.ts", stringtestutil.Dedent(` export var myClassWithError = class { tags() { } @@ -1816,7 +1816,7 @@ func TestBuildProgramUpdates(t *testing.T) { }, { caption: "Change fileWithoutError", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileTextAll("/user/username/projects/solution/app/fileWithoutError.ts", "myClass", "myClass2") }, }, @@ -1839,7 +1839,7 @@ func TestBuildProgramUpdates(t *testing.T) { edits: []*tscEdit{ { caption: "Change tsconfig to set noUnusedParameters to false", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError( `/user/username/projects/myproject/tsconfig.json`, stringtestutil.Dedent(` @@ -1924,7 +1924,7 @@ func TestBuildProgramUpdates(t *testing.T) { edits: []*tscEdit{ { caption: "Modify alpha config", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/user/username/projects/project/alpha.tsconfig.json", stringtestutil.Dedent(` { "compilerOptions": { @@ -1935,7 +1935,7 @@ func TestBuildProgramUpdates(t *testing.T) { }, { caption: "change bravo config", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/user/username/projects/project/bravo.tsconfig.json", stringtestutil.Dedent(` { "extends": "./alpha.tsconfig.json", @@ -1945,7 +1945,7 @@ func TestBuildProgramUpdates(t *testing.T) { }, { caption: "project 2 extends alpha", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/user/username/projects/project/project2.tsconfig.json", stringtestutil.Dedent(` { "extends": "./alpha.tsconfig.json", @@ -1954,13 +1954,13 @@ func TestBuildProgramUpdates(t *testing.T) { }, { caption: "update aplha config", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/user/username/projects/project/alpha.tsconfig.json", "{}", false) }, }, { caption: "Modify extendsConfigFile2", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/user/username/projects/project/extendsConfig2.tsconfig.json", stringtestutil.Dedent(` { "compilerOptions": { "strictNullChecks": true } @@ -1969,7 +1969,7 @@ func TestBuildProgramUpdates(t *testing.T) { }, { caption: "Modify project 3", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/user/username/projects/project/project3.tsconfig.json", stringtestutil.Dedent(` { "extends": ["./extendsConfig1.tsconfig.json", "./extendsConfig2.tsconfig.json"], @@ -1980,7 +1980,7 @@ func TestBuildProgramUpdates(t *testing.T) { }, { caption: "Delete extendedConfigFile2 and report error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.removeNoError("/user/username/projects/project/extendsConfig2.tsconfig.json") }, }, @@ -2038,7 +2038,7 @@ func TestBuildProgramUpdates(t *testing.T) { edits: []*tscEdit{ { caption: "Remove project2 from base config", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/user/username/projects/project/tsconfig.json", stringtestutil.Dedent(` { "references": [ @@ -2083,7 +2083,7 @@ func TestBuildProgramUpdates(t *testing.T) { edits: []*tscEdit{ { caption: "dts doesnt change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/home/src/workspaces/project/lib/foo.ts", "const Bar = 10;") }, }, @@ -2114,7 +2114,7 @@ func TestBuildProgramUpdates(t *testing.T) { edits: []*tscEdit{ { caption: "dts doesnt change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/home/src/workspaces/project/lib/foo.ts", "const Bar = 10;") }, }, @@ -2167,14 +2167,14 @@ func TestBuildProjectsBuilding(t *testing.T) { edits := []*tscEdit{ { caption: "dts doesn't change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile(`/user/username/projects/myproject/pkg0/index.ts`, `const someConst2 = 10;`) }, }, noChange, { caption: "dts change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile(`/user/username/projects/myproject/pkg0/index.ts`, `export const someConst = 10;`) }, }, @@ -2412,13 +2412,13 @@ func TestBuildReexport(t *testing.T) { edits: []*tscEdit{ { caption: "Introduce error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText(`/user/username/projects/reexport/src/pure/session.ts`, "// ", "") }, }, { caption: "Fix error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText(`/user/username/projects/reexport/src/pure/session.ts`, "bar: ", "// bar: ") }, }, @@ -2692,14 +2692,14 @@ func TestBuildRoots(t *testing.T) { noChange, { caption: "edit logging file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/home/src/workspaces/solution/projects/shared/src/logging.ts", "export const x = 10;") }, }, noChange, { caption: "delete random file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.removeNoError("/home/src/workspaces/solution/projects/shared/src/random.ts") }, }, @@ -2722,7 +2722,7 @@ func TestBuildRoots(t *testing.T) { edits: []*tscEdit{ { caption: "delete file1", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.removeNoError("/home/src/workspaces/project/file1.ts") sys.removeNoError("/home/src/workspaces/project/file1.js") sys.removeNoError("/home/src/workspaces/project/file1.d.ts") @@ -2747,7 +2747,7 @@ func TestBuildRoots(t *testing.T) { edits: []*tscEdit{ { caption: "delete file1", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.removeNoError("/home/src/workspaces/project/file1.ts") sys.removeNoError("/home/src/workspaces/project/file1.js") sys.removeNoError("/home/src/workspaces/project/file1.d.ts") @@ -2774,7 +2774,7 @@ func TestBuildRoots(t *testing.T) { edits: []*tscEdit{ { caption: "delete file1", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.removeNoError("/home/src/workspaces/project/file1.ts") sys.removeNoError("/home/src/workspaces/project/file1.js") sys.removeNoError("/home/src/workspaces/project/file1.d.ts") @@ -2814,7 +2814,7 @@ func TestBuildRoots(t *testing.T) { edits: []*tscEdit{ { caption: "delete file1", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.removeNoError("/home/src/workspaces/project/file1.ts") sys.removeNoError("/home/src/workspaces/project/file1.js") sys.removeNoError("/home/src/workspaces/project/file1.d.ts") @@ -2947,7 +2947,7 @@ func TestBuildSample(t *testing.T) { []*tscEdit{ { caption: "fix error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/user/username/projects/sample1/core/index.ts", "multiply();", "") }, }, @@ -2979,7 +2979,7 @@ func TestBuildSample(t *testing.T) { []*tscEdit{ { caption: "fix error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/user/username/projects/sample1/core/index.ts", "multiply();", "") }, }, @@ -2992,7 +2992,7 @@ func TestBuildSample(t *testing.T) { return []*tscEdit{ { caption: "incremental-declaration-changes", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile( "/user/username/projects/sample1/core/index.ts", ` @@ -3002,7 +3002,7 @@ export class someClass { }`, }, { caption: "incremental-declaration-doesnt-change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile( "/user/username/projects/sample1/core/index.ts", ` @@ -3017,19 +3017,19 @@ class someClass2 { }`, return []*tscEdit{ { caption: "Make change to core", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/user/username/projects/sample1/core/index.ts", "\nexport class someClass { }") }, }, { caption: "Revert core file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/user/username/projects/sample1/core/index.ts", "\nexport class someClass { }", "") }, }, { caption: "Make two changes", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/user/username/projects/sample1/core/index.ts", "\nexport class someClass { }") sys.appendFile("/user/username/projects/sample1/core/index.ts", "\nexport class someClass2 { }") }, @@ -3040,7 +3040,7 @@ class someClass2 { }`, return []*tscEdit{ { caption: "Make local change to core", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/user/username/projects/sample1/core/index.ts", "\nfunction foo() { }") }, }, @@ -3050,13 +3050,13 @@ class someClass2 { }`, return []*tscEdit{ { caption: "Change to new File and build core", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/user/username/projects/sample1/core/newfile.ts", `export const newFileConst = 30;`, false) }, }, { caption: "Change to new File and build core", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/user/username/projects/sample1/core/newfile.ts", "\nexport class someClass2 { }", false) }, }, @@ -3090,20 +3090,20 @@ class someClass2 { }`, edits: []*tscEdit{ { caption: "change logic", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/user/username/projects/sample1/logic/index.ts", "\nlet y: string = 10;") }, }, { caption: "change core", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/user/username/projects/sample1/core/index.ts", "\nlet x: string = 10;") }, expectedDiff: expectedDiffWithLogicError, }, { caption: "fix error in logic", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/user/username/projects/sample1/logic/index.ts", "\nlet y: string = 10;", "") }, }, @@ -3203,20 +3203,20 @@ class someClass2 { }`, { // Update a file in the leaf node (tests), only it should rebuild the last one caption: "Only builds the leaf node project", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/user/username/projects/sample1/tests/index.ts", "const m = 10;", false) }, }, { // Update a file in the parent (without affecting types), should get fast downstream builds caption: "Detects type-only changes in upstream projects", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/user/username/projects/sample1/core/index.ts", "HELLO WORLD", "WELCOME PLANET") }, }, { caption: "rebuilds when tsconfig changes", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/user/username/projects/sample1/tests/tsconfig.json", `"composite": true`, `"composite": true, "target": "es2020"`) }, }, @@ -3230,7 +3230,7 @@ class someClass2 { }`, edits: []*tscEdit{ { caption: "upstream project changes without changing file text", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { err := sys.FS().Chtimes("/user/username/projects/sample1/core/index.ts", time.Time{}, sys.Now()) if err != nil { panic(err) @@ -3247,13 +3247,13 @@ class someClass2 { }`, edits: []*tscEdit{ { caption: "Disable declarationMap", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/user/username/projects/sample1/core/tsconfig.json", `"declarationMap": true,`, `"declarationMap": false,`) }, }, { caption: "Enable declarationMap", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/user/username/projects/sample1/core/tsconfig.json", `"declarationMap": false,`, `"declarationMap": true,`) }, }, @@ -3294,7 +3294,7 @@ class someClass2 { }`, edits: []*tscEdit{ { caption: "tsbuildinfo written has error", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { // This is to ensure the non incremental doesnt crash - as it wont have tsbuildInfo if !sys.forIncrementalCorrectness { sys.prependFile("/home/src/workspaces/project/tsconfig.tsbuildinfo", "Some random string") @@ -3312,7 +3312,7 @@ class someClass2 { }`, edits: []*tscEdit{ { caption: "convert tsbuildInfo version to something that is say to previous version", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { // This is to ensure the non incremental doesnt crash - as it wont have tsbuildInfo if !sys.forIncrementalCorrectness { sys.replaceFileText("/user/username/projects/sample1/core/tsconfig.tsbuildinfo", fmt.Sprintf(`"version":"%s"`, harnessutil.FakeTSVersion), fmt.Sprintf(`"version":"%s"`, "FakeTsPreviousVersion")) @@ -3340,7 +3340,7 @@ class someClass2 { }`, edits: []*tscEdit{ { caption: "change extended file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/user/username/projects/sample1/tests/tsconfig.base.json", stringtestutil.Dedent(` { "compilerOptions": { } @@ -3396,7 +3396,7 @@ class someClass2 { }`, []*tscEdit{ { caption: "when logic config changes declaration dir", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText( "/user/username/projects/sample1/logic/tsconfig.json", `"declaration": true,`, @@ -3440,7 +3440,7 @@ class someClass2 { }`, edits: []*tscEdit{ { caption: "incremental-declaration-changes", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/user/username/projects/sample1/core/tsconfig.json", `"incremental": true,`, `"incremental": true, "declaration": true,`) }, }, @@ -3468,7 +3468,7 @@ class someClass2 { }`, edits: []*tscEdit{ { caption: "incremental-declaration-changes", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/user/username/projects/sample1/core/tsconfig.json", `esnext`, `es5`) }, }, @@ -3490,7 +3490,7 @@ class someClass2 { }`, edits: []*tscEdit{ { caption: "incremental-declaration-changes", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/user/username/projects/sample1/core/tsconfig.json", `node18`, `nodenext`) }, }, @@ -3519,7 +3519,7 @@ class someClass2 { }`, edits: []*tscEdit{ { caption: "incremental-declaration-changes", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/user/username/projects/sample1/tests/tsconfig.json", `"esModuleInterop": false`, `"esModuleInterop": true`) }, }, @@ -3605,7 +3605,7 @@ class someClass2 { }`, edits: []*tscEdit{ { caption: "Write logic", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/user/username/projects/sample1/logic/tsconfig.json", getLogicConfig(), false) }, }, @@ -3622,13 +3622,13 @@ class someClass2 { }`, edits: []*tscEdit{ { caption: "Make non dts change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.appendFile("/user/username/projects/sample1/logic/index.ts", "\nfunction someFn() { }") }, }, { caption: "Make dts change", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/user/username/projects/sample1/logic/index.ts", "\nfunction someFn() { }", "\nexport function someFn() { }") }, }, @@ -3643,7 +3643,7 @@ class someClass2 { }`, noChange, { caption: "Add new file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/user/username/projects/sample1/core/file3.ts", `export const y = 10;`, false) }, }, @@ -3667,7 +3667,7 @@ class someClass2 { }`, noChange, { caption: "Add new file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.writeFileNoError("/user/username/projects/sample1/core/file3.ts", `export const y = 10;`, false) }, }, @@ -3872,7 +3872,7 @@ func TestBuildSolutionProject(t *testing.T) { edits: []*tscEdit{ { caption: "modify project3 file", - edit: func(sys *testSys) { + edit: func(sys *TestSys) { sys.replaceFileText("/home/src/workspaces/solution/project3/src/c.ts", "c = ", "cc = ") }, }, diff --git a/internal/execute/tsctests/tscwatch_test.go b/internal/execute/tsctests/tscwatch_test.go index 58517bdb35..10344fdf29 100644 --- a/internal/execute/tsctests/tscwatch_test.go +++ b/internal/execute/tsctests/tscwatch_test.go @@ -70,29 +70,29 @@ func noEmitWatchTestInput( "/home/src/workspaces/project/tsconfig.json": tsconfigText, }, edits: []*tscEdit{ - newTscEdit("fix error", func(sys *testSys) { + newTscEdit("fix error", func(sys *TestSys) { sys.writeFileNoError("/home/src/workspaces/project/a.ts", `const a = "hello";`, false) }), - newTscEdit("emit after fixing error", func(sys *testSys) { + newTscEdit("emit after fixing error", func(sys *TestSys) { sys.writeFileNoError("/home/src/workspaces/project/tsconfig.json", toTsconfig("", optionString), false) }), - newTscEdit("no emit run after fixing error", func(sys *testSys) { + newTscEdit("no emit run after fixing error", func(sys *TestSys) { sys.writeFileNoError("/home/src/workspaces/project/tsconfig.json", toTsconfig(noEmitOpt, optionString), false) }), - newTscEdit("introduce error", func(sys *testSys) { + newTscEdit("introduce error", func(sys *TestSys) { sys.writeFileNoError("/home/src/workspaces/project/a.ts", aText, false) }), - newTscEdit("emit when error", func(sys *testSys) { + newTscEdit("emit when error", func(sys *TestSys) { sys.writeFileNoError("/home/src/workspaces/project/tsconfig.json", toTsconfig("", optionString), false) }), - newTscEdit("no emit run when error", func(sys *testSys) { + newTscEdit("no emit run when error", func(sys *TestSys) { sys.writeFileNoError("/home/src/workspaces/project/tsconfig.json", toTsconfig(noEmitOpt, optionString), false) }), }, } } -func newTscEdit(name string, edit func(sys *testSys)) *tscEdit { +func newTscEdit(name string, edit func(sys *TestSys)) *tscEdit { return &tscEdit{name, []string{}, edit, ""} } diff --git a/internal/format/context.go b/internal/format/context.go index aae5b935bf..bb059e45a4 100644 --- a/internal/format/context.go +++ b/internal/format/context.go @@ -85,7 +85,7 @@ func GetDefaultFormatCodeSettings(newLineCharacter string) *FormatCodeSettings { } } -type formattingContext struct { +type FormattingContext struct { currentTokenSpan TextRangeWithKind nextTokenSpan TextRangeWithKind contextNode *ast.Node @@ -105,8 +105,8 @@ type formattingContext struct { scanner *scanner.Scanner } -func NewFormattingContext(file *ast.SourceFile, kind FormatRequestKind, options *FormatCodeSettings) *formattingContext { - res := &formattingContext{ +func NewFormattingContext(file *ast.SourceFile, kind FormatRequestKind, options *FormatCodeSettings) *FormattingContext { + res := &FormattingContext{ SourceFile: file, FormattingRequestKind: kind, Options: options, @@ -117,7 +117,7 @@ func NewFormattingContext(file *ast.SourceFile, kind FormatRequestKind, options return res } -func (this *formattingContext) UpdateContext(cur TextRangeWithKind, curParent *ast.Node, next TextRangeWithKind, nextParent *ast.Node, commonParent *ast.Node) { +func (this *FormattingContext) UpdateContext(cur TextRangeWithKind, curParent *ast.Node, next TextRangeWithKind, nextParent *ast.Node, commonParent *ast.Node) { if curParent == nil { panic("nil current range node parent in update context") } @@ -141,14 +141,14 @@ func (this *formattingContext) UpdateContext(cur TextRangeWithKind, curParent *a this.nextNodeBlockIsOnOneLine = core.TSUnknown } -func (this *formattingContext) rangeIsOnOneLine(node core.TextRange) core.Tristate { +func (this *FormattingContext) rangeIsOnOneLine(node core.TextRange) core.Tristate { if rangeIsOnOneLine(node, this.SourceFile) { return core.TSTrue } return core.TSFalse } -func (this *formattingContext) nodeIsOnOneLine(node *ast.Node) core.Tristate { +func (this *FormattingContext) nodeIsOnOneLine(node *ast.Node) core.Tristate { return this.rangeIsOnOneLine(withTokenStart(node, this.SourceFile)) } @@ -157,7 +157,7 @@ func withTokenStart(loc *ast.Node, file *ast.SourceFile) core.TextRange { return core.NewTextRange(startPos, loc.End()) } -func (this *formattingContext) blockIsOnOneLine(node *ast.Node) core.Tristate { +func (this *FormattingContext) blockIsOnOneLine(node *ast.Node) core.Tristate { // In strada, this relies on token child manifesting - we just use the scanner here, // so this will have a differing performance profile. Is this OK? Needs profiling to know. this.scanner.ResetPos(node.Pos()) @@ -179,35 +179,35 @@ func (this *formattingContext) blockIsOnOneLine(node *ast.Node) core.Tristate { return core.TSFalse } -func (this *formattingContext) ContextNodeAllOnSameLine() bool { +func (this *FormattingContext) ContextNodeAllOnSameLine() bool { if this.contextNodeAllOnSameLine == core.TSUnknown { this.contextNodeAllOnSameLine = this.nodeIsOnOneLine(this.contextNode) } return this.contextNodeAllOnSameLine == core.TSTrue } -func (this *formattingContext) NextNodeAllOnSameLine() bool { +func (this *FormattingContext) NextNodeAllOnSameLine() bool { if this.nextNodeAllOnSameLine == core.TSUnknown { this.nextNodeAllOnSameLine = this.nodeIsOnOneLine(this.nextTokenParent) } return this.nextNodeAllOnSameLine == core.TSTrue } -func (this *formattingContext) TokensAreOnSameLine() bool { +func (this *FormattingContext) TokensAreOnSameLine() bool { if this.tokensAreOnSameLine == core.TSUnknown { this.tokensAreOnSameLine = this.rangeIsOnOneLine(core.NewTextRange(this.currentTokenSpan.Loc.Pos(), this.nextTokenSpan.Loc.End())) } return this.tokensAreOnSameLine == core.TSTrue } -func (this *formattingContext) ContextNodeBlockIsOnOneLine() bool { +func (this *FormattingContext) ContextNodeBlockIsOnOneLine() bool { if this.contextNodeBlockIsOnOneLine == core.TSUnknown { this.contextNodeBlockIsOnOneLine = this.blockIsOnOneLine(this.contextNode) } return this.contextNodeBlockIsOnOneLine == core.TSTrue } -func (this *formattingContext) NextNodeBlockIsOnOneLine() bool { +func (this *FormattingContext) NextNodeBlockIsOnOneLine() bool { if this.nextNodeBlockIsOnOneLine == core.TSUnknown { this.nextNodeBlockIsOnOneLine = this.blockIsOnOneLine(this.nextTokenParent) } diff --git a/internal/format/rule.go b/internal/format/rule.go index 87e7f8f426..b61e883661 100644 --- a/internal/format/rule.go +++ b/internal/format/rule.go @@ -80,7 +80,7 @@ func toTokenRange(e any) tokenRange { panic("Unknown argument type passed to toTokenRange - only ast.Kind, []ast.Kind, and tokenRange supported") } -type contextPredicate = func(ctx *formattingContext) bool +type contextPredicate = func(ctx *FormattingContext) bool var anyContext = []contextPredicate{} diff --git a/internal/format/rulecontext.go b/internal/format/rulecontext.go index 7b91c7bfff..1192ccba5b 100644 --- a/internal/format/rulecontext.go +++ b/internal/format/rulecontext.go @@ -97,7 +97,7 @@ func indentSwitchCaseOption(options *FormatCodeSettings) core.Tristate { } func optionEquals[T comparable](optionName anyOptionSelector[T], optionValue T) contextPredicate { - return func(context *formattingContext) bool { + return func(context *FormattingContext) bool { if context.Options == nil { return false } @@ -106,7 +106,7 @@ func optionEquals[T comparable](optionName anyOptionSelector[T], optionValue T) } func isOptionEnabled(optionName optionSelector) contextPredicate { - return func(context *formattingContext) bool { + return func(context *FormattingContext) bool { if context.Options == nil { return false } @@ -115,7 +115,7 @@ func isOptionEnabled(optionName optionSelector) contextPredicate { } func isOptionDisabled(optionName optionSelector) contextPredicate { - return func(context *formattingContext) bool { + return func(context *FormattingContext) bool { if context.Options == nil { return true } @@ -124,7 +124,7 @@ func isOptionDisabled(optionName optionSelector) contextPredicate { } func isOptionDisabledOrUndefined(optionName optionSelector) contextPredicate { - return func(context *formattingContext) bool { + return func(context *FormattingContext) bool { if context.Options == nil { return true } @@ -133,7 +133,7 @@ func isOptionDisabledOrUndefined(optionName optionSelector) contextPredicate { } func isOptionDisabledOrUndefinedOrTokensOnSameLine(optionName optionSelector) contextPredicate { - return func(context *formattingContext) bool { + return func(context *FormattingContext) bool { if context.Options == nil { return true } @@ -142,7 +142,7 @@ func isOptionDisabledOrUndefinedOrTokensOnSameLine(optionName optionSelector) co } func isOptionEnabledOrUndefined(optionName optionSelector) contextPredicate { - return func(context *formattingContext) bool { + return func(context *FormattingContext) bool { if context.Options == nil { return true } @@ -150,15 +150,15 @@ func isOptionEnabledOrUndefined(optionName optionSelector) contextPredicate { } } -func isForContext(context *formattingContext) bool { +func isForContext(context *FormattingContext) bool { return context.contextNode.Kind == ast.KindForStatement } -func isNotForContext(context *formattingContext) bool { +func isNotForContext(context *FormattingContext) bool { return !isForContext(context) } -func isBinaryOpContext(context *formattingContext) bool { +func isBinaryOpContext(context *FormattingContext) bool { switch context.contextNode.Kind { case ast.KindBinaryExpression: return context.contextNode.AsBinaryExpression().OperatorToken.Kind != ast.KindCommaToken @@ -207,15 +207,15 @@ func isBinaryOpContext(context *formattingContext) bool { return false } -func isNotBinaryOpContext(context *formattingContext) bool { +func isNotBinaryOpContext(context *FormattingContext) bool { return !isBinaryOpContext(context) } -func isNotTypeAnnotationContext(context *formattingContext) bool { +func isNotTypeAnnotationContext(context *FormattingContext) bool { return !isTypeAnnotationContext(context) } -func isTypeAnnotationContext(context *formattingContext) bool { +func isTypeAnnotationContext(context *FormattingContext) bool { contextKind := context.contextNode.Kind return contextKind == ast.KindPropertyDeclaration || contextKind == ast.KindPropertySignature || @@ -224,47 +224,47 @@ func isTypeAnnotationContext(context *formattingContext) bool { ast.IsFunctionLikeKind(contextKind) } -func isOptionalPropertyContext(context *formattingContext) bool { +func isOptionalPropertyContext(context *FormattingContext) bool { return ast.IsPropertyDeclaration(context.contextNode) && context.contextNode.AsPropertyDeclaration().PostfixToken != nil && context.contextNode.AsPropertyDeclaration().PostfixToken.Kind == ast.KindQuestionToken } -func isNonOptionalPropertyContext(context *formattingContext) bool { +func isNonOptionalPropertyContext(context *FormattingContext) bool { return !isOptionalPropertyContext(context) } -func isConditionalOperatorContext(context *formattingContext) bool { +func isConditionalOperatorContext(context *FormattingContext) bool { return context.contextNode.Kind == ast.KindConditionalExpression || context.contextNode.Kind == ast.KindConditionalType } -func isSameLineTokenOrBeforeBlockContext(context *formattingContext) bool { +func isSameLineTokenOrBeforeBlockContext(context *FormattingContext) bool { return context.TokensAreOnSameLine() || isBeforeBlockContext(context) } -func isBraceWrappedContext(context *formattingContext) bool { +func isBraceWrappedContext(context *FormattingContext) bool { return context.contextNode.Kind == ast.KindObjectBindingPattern || context.contextNode.Kind == ast.KindMappedType || isSingleLineBlockContext(context) } // This check is done before an open brace in a control construct, a function, or a typescript block declaration -func isBeforeMultilineBlockContext(context *formattingContext) bool { +func isBeforeMultilineBlockContext(context *FormattingContext) bool { return isBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine()) } -func isMultilineBlockContext(context *formattingContext) bool { +func isMultilineBlockContext(context *FormattingContext) bool { return isBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()) } -func isSingleLineBlockContext(context *formattingContext) bool { +func isSingleLineBlockContext(context *FormattingContext) bool { return isBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()) } -func isBlockContext(context *formattingContext) bool { +func isBlockContext(context *FormattingContext) bool { return nodeIsBlockContext(context.contextNode) } -func isBeforeBlockContext(context *formattingContext) bool { +func isBeforeBlockContext(context *FormattingContext) bool { return nodeIsBlockContext(context.nextTokenParent) } @@ -286,7 +286,7 @@ func nodeIsBlockContext(node *ast.Node) bool { return false } -func isFunctionDeclContext(context *formattingContext) bool { +func isFunctionDeclContext(context *FormattingContext) bool { switch context.contextNode.Kind { case ast.KindFunctionDeclaration, ast.KindMethodDeclaration, @@ -312,15 +312,15 @@ func isFunctionDeclContext(context *formattingContext) bool { return false } -func isNotFunctionDeclContext(context *formattingContext) bool { +func isNotFunctionDeclContext(context *FormattingContext) bool { return !isFunctionDeclContext(context) } -func isFunctionDeclarationOrFunctionExpressionContext(context *formattingContext) bool { +func isFunctionDeclarationOrFunctionExpressionContext(context *FormattingContext) bool { return context.contextNode.Kind == ast.KindFunctionDeclaration || context.contextNode.Kind == ast.KindFunctionExpression } -func isTypeScriptDeclWithBlockContext(context *formattingContext) bool { +func isTypeScriptDeclWithBlockContext(context *FormattingContext) bool { return nodeIsTypeScriptDeclWithBlockContext(context.contextNode) } @@ -342,7 +342,7 @@ func nodeIsTypeScriptDeclWithBlockContext(node *ast.Node) bool { return false } -func isAfterCodeBlockContext(context *formattingContext) bool { +func isAfterCodeBlockContext(context *FormattingContext) bool { switch context.currentTokenParent.Kind { case ast.KindClassDeclaration, ast.KindModuleDeclaration, @@ -361,7 +361,7 @@ func isAfterCodeBlockContext(context *formattingContext) bool { return false } -func isControlDeclContext(context *formattingContext) bool { +func isControlDeclContext(context *FormattingContext) bool { switch context.contextNode.Kind { case ast.KindIfStatement, ast.KindSwitchStatement, @@ -383,83 +383,83 @@ func isControlDeclContext(context *formattingContext) bool { } } -func isObjectContext(context *formattingContext) bool { +func isObjectContext(context *FormattingContext) bool { return context.contextNode.Kind == ast.KindObjectLiteralExpression } -func isFunctionCallContext(context *formattingContext) bool { +func isFunctionCallContext(context *FormattingContext) bool { return context.contextNode.Kind == ast.KindCallExpression } -func isNewContext(context *formattingContext) bool { +func isNewContext(context *FormattingContext) bool { return context.contextNode.Kind == ast.KindNewExpression } -func isFunctionCallOrNewContext(context *formattingContext) bool { +func isFunctionCallOrNewContext(context *FormattingContext) bool { return isFunctionCallContext(context) || isNewContext(context) } -func isPreviousTokenNotComma(context *formattingContext) bool { +func isPreviousTokenNotComma(context *FormattingContext) bool { return context.currentTokenSpan.Kind != ast.KindCommaToken } -func isNextTokenNotCloseBracket(context *formattingContext) bool { +func isNextTokenNotCloseBracket(context *FormattingContext) bool { return context.nextTokenSpan.Kind != ast.KindCloseBracketToken } -func isNextTokenNotCloseParen(context *formattingContext) bool { +func isNextTokenNotCloseParen(context *FormattingContext) bool { return context.nextTokenSpan.Kind != ast.KindCloseParenToken } -func isArrowFunctionContext(context *formattingContext) bool { +func isArrowFunctionContext(context *FormattingContext) bool { return context.contextNode.Kind == ast.KindArrowFunction } -func isImportTypeContext(context *formattingContext) bool { +func isImportTypeContext(context *FormattingContext) bool { return context.contextNode.Kind == ast.KindImportType } -func isNonJsxSameLineTokenContext(context *formattingContext) bool { +func isNonJsxSameLineTokenContext(context *FormattingContext) bool { return context.TokensAreOnSameLine() && context.contextNode.Kind != ast.KindJsxText } -func isNonJsxTextContext(context *formattingContext) bool { +func isNonJsxTextContext(context *FormattingContext) bool { return context.contextNode.Kind != ast.KindJsxText } -func isNonJsxElementOrFragmentContext(context *formattingContext) bool { +func isNonJsxElementOrFragmentContext(context *FormattingContext) bool { return context.contextNode.Kind != ast.KindJsxElement && context.contextNode.Kind != ast.KindJsxFragment } -func isJsxExpressionContext(context *formattingContext) bool { +func isJsxExpressionContext(context *FormattingContext) bool { return context.contextNode.Kind == ast.KindJsxExpression || context.contextNode.Kind == ast.KindJsxSpreadAttribute } -func isNextTokenParentJsxAttribute(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) } -func isJsxAttributeContext(context *formattingContext) bool { +func isJsxAttributeContext(context *FormattingContext) bool { return context.contextNode.Kind == ast.KindJsxAttribute } -func isNextTokenParentNotJsxNamespacedName(context *formattingContext) bool { +func isNextTokenParentNotJsxNamespacedName(context *FormattingContext) bool { return context.nextTokenParent.Kind != ast.KindJsxNamespacedName } -func isNextTokenParentJsxNamespacedName(context *formattingContext) bool { +func isNextTokenParentJsxNamespacedName(context *FormattingContext) bool { return context.nextTokenParent.Kind == ast.KindJsxNamespacedName } -func isJsxSelfClosingElementContext(context *formattingContext) bool { +func isJsxSelfClosingElementContext(context *FormattingContext) bool { return context.contextNode.Kind == ast.KindJsxSelfClosingElement } -func isNotBeforeBlockInFunctionDeclarationContext(context *formattingContext) bool { +func isNotBeforeBlockInFunctionDeclarationContext(context *FormattingContext) bool { return !isFunctionDeclContext(context) && !isBeforeBlockContext(context) } -func isEndOfDecoratorContextOnSameLine(context *formattingContext) bool { +func isEndOfDecoratorContextOnSameLine(context *FormattingContext) bool { return context.TokensAreOnSameLine() && ast.HasDecorators(context.contextNode) && nodeIsInDecoratorContext(context.currentTokenParent) && @@ -473,24 +473,24 @@ func nodeIsInDecoratorContext(node *ast.Node) bool { return node != nil && node.Kind == ast.KindDecorator } -func isStartOfVariableDeclarationList(context *formattingContext) bool { +func isStartOfVariableDeclarationList(context *FormattingContext) bool { return context.currentTokenParent.Kind == ast.KindVariableDeclarationList && scanner.GetTokenPosOfNode(context.currentTokenParent, context.SourceFile, false) == context.currentTokenSpan.Loc.Pos() } -func isNotFormatOnEnter(context *formattingContext) bool { +func isNotFormatOnEnter(context *FormattingContext) bool { return context.FormattingRequestKind != FormatRequestKindFormatOnEnter } -func isModuleDeclContext(context *formattingContext) bool { +func isModuleDeclContext(context *FormattingContext) bool { return context.contextNode.Kind == ast.KindModuleDeclaration } -func isObjectTypeContext(context *formattingContext) bool { +func isObjectTypeContext(context *FormattingContext) bool { return context.contextNode.Kind == ast.KindTypeLiteral // && context.contextNode.parent.Kind != ast.KindInterfaceDeclaration; } -func isConstructorSignatureContext(context *formattingContext) bool { +func isConstructorSignatureContext(context *FormattingContext) bool { return context.contextNode.Kind == ast.KindConstructSignature } @@ -521,36 +521,36 @@ func isTypeArgumentOrParameterOrAssertion(token TextRangeWithKind, parent *ast.N } } -func isTypeArgumentOrParameterOrAssertionContext(context *formattingContext) bool { +func isTypeArgumentOrParameterOrAssertionContext(context *FormattingContext) bool { return isTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) || isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent) } -func isTypeAssertionContext(context *formattingContext) bool { +func isTypeAssertionContext(context *FormattingContext) bool { return context.contextNode.Kind == ast.KindTypeAssertionExpression } -func isNonTypeAssertionContext(context *formattingContext) bool { +func isNonTypeAssertionContext(context *FormattingContext) bool { return !isTypeAssertionContext(context) } -func isVoidOpContext(context *formattingContext) bool { +func isVoidOpContext(context *FormattingContext) bool { return context.currentTokenSpan.Kind == ast.KindVoidKeyword && context.currentTokenParent.Kind == ast.KindVoidExpression } -func isYieldOrYieldStarWithOperand(context *formattingContext) bool { +func isYieldOrYieldStarWithOperand(context *FormattingContext) bool { return context.contextNode.Kind == ast.KindYieldExpression && context.contextNode.AsYieldExpression().Expression != nil } -func isNonNullAssertionContext(context *formattingContext) bool { +func isNonNullAssertionContext(context *FormattingContext) bool { return context.contextNode.Kind == ast.KindNonNullExpression } -func isNotStatementConditionContext(context *formattingContext) bool { +func isNotStatementConditionContext(context *FormattingContext) bool { return !isStatementConditionContext(context) } -func isStatementConditionContext(context *formattingContext) bool { +func isStatementConditionContext(context *FormattingContext) bool { switch context.contextNode.Kind { case ast.KindIfStatement, ast.KindForStatement, @@ -565,7 +565,7 @@ func isStatementConditionContext(context *formattingContext) bool { } } -func isSemicolonDeletionContext(context *formattingContext) bool { +func isSemicolonDeletionContext(context *FormattingContext) bool { nextTokenKind := context.nextTokenSpan.Kind nextTokenStart := context.nextTokenSpan.Loc.Pos() if ast.IsTrivia(nextTokenKind) { @@ -633,11 +633,11 @@ func isSemicolonDeletionContext(context *formattingContext) bool { nextTokenKind != ast.KindDotToken } -func isSemicolonInsertionContext(context *formattingContext) bool { +func isSemicolonInsertionContext(context *FormattingContext) bool { return lsutil.PositionIsASICandidate(context.currentTokenSpan.Loc.End(), context.currentTokenParent, context.SourceFile) } -func isNotPropertyAccessOnIntegerLiteral(context *formattingContext) bool { +func isNotPropertyAccessOnIntegerLiteral(context *FormattingContext) bool { return !ast.IsPropertyAccessExpression(context.contextNode) || !ast.IsNumericLiteral(context.contextNode.Expression()) || strings.Contains(context.contextNode.Expression().Text(), ".") diff --git a/internal/format/rulesmap.go b/internal/format/rulesmap.go index c511ddc19e..9d3ea50ae6 100644 --- a/internal/format/rulesmap.go +++ b/internal/format/rulesmap.go @@ -8,7 +8,7 @@ import ( "github.com/microsoft/typescript-go/internal/debug" ) -func getRules(context *formattingContext, rules []*ruleImpl) []*ruleImpl { +func getRules(context *FormattingContext, rules []*ruleImpl) []*ruleImpl { bucket := getRulesMap()[getRuleBucketIndex(context.currentTokenSpan.Kind, context.nextTokenSpan.Kind)] if len(bucket) > 0 { ruleActionMask := ruleActionNone diff --git a/internal/format/span.go b/internal/format/span.go index 3a1ea475cd..de5b4df29a 100644 --- a/internal/format/span.go +++ b/internal/format/span.go @@ -159,7 +159,7 @@ type formatSpanWorker struct { ctx context.Context formattingScanner *formattingScanner - formattingContext *formattingContext + formattingContext *FormattingContext edits []core.TextChange previousRange TextRangeWithKind diff --git a/internal/fourslash/fourslash.go b/internal/fourslash/fourslash.go index 93f61817ab..2665ff137e 100644 --- a/internal/fourslash/fourslash.go +++ b/internal/fourslash/fourslash.go @@ -2171,6 +2171,4 @@ func (f *FourslashTest) verifyBaselines(t *testing.T) { } } -type anyTextEdits *[]*lsproto.TextEdit - -var AnyTextEdits = anyTextEdits(nil) +var AnyTextEdits *[]*lsproto.TextEdit diff --git a/internal/ls/autoimports.go b/internal/ls/autoimports.go index 1e586cc070..15bf626939 100644 --- a/internal/ls/autoimports.go +++ b/internal/ls/autoimports.go @@ -69,7 +69,7 @@ type CachedSymbolExportInfo struct { isFromPackageJson bool } -type exportInfoMap struct { +type ExportInfoMap struct { exportInfo collections.OrderedMap[ExportInfoMapKey, []*CachedSymbolExportInfo] symbols map[int]symbolExportEntry exportInfoId int @@ -82,20 +82,20 @@ type exportInfoMap struct { // !!! onFileChanged func(oldSourceFile *ast.SourceFile, newSourceFile *ast.SourceFile, typeAcquisitionEnabled bool) bool } -func (e *exportInfoMap) clear() { +func (e *ExportInfoMap) clear() { e.symbols = map[int]symbolExportEntry{} e.exportInfo = collections.OrderedMap[ExportInfoMapKey, []*CachedSymbolExportInfo]{} e.usableByFileName = "" } -func (e *exportInfoMap) get(importingFile tspath.Path, ch *checker.Checker, key ExportInfoMapKey) []*SymbolExportInfo { +func (e *ExportInfoMap) get(importingFile tspath.Path, ch *checker.Checker, key ExportInfoMapKey) []*SymbolExportInfo { if e.usableByFileName != importingFile { return nil } return core.Map(e.exportInfo.GetOrZero(key), func(info *CachedSymbolExportInfo) *SymbolExportInfo { return e.rehydrateCachedInfo(ch, info) }) } -func (e *exportInfoMap) add( +func (e *ExportInfoMap) add( importingFile tspath.Path, symbol *ast.Symbol, symbolTableKey string, @@ -216,7 +216,7 @@ func (e *exportInfoMap) add( e.exportInfo.Set(key, infos) } -func (e *exportInfoMap) search( +func (e *ExportInfoMap) search( ch *checker.Checker, importingFile tspath.Path, preferCapitalized bool, @@ -248,7 +248,7 @@ func (e *exportInfoMap) search( return nil } -func (e *exportInfoMap) isNotShadowedByDeeperNodeModulesPackage(info *SymbolExportInfo, packageName string) bool { +func (e *ExportInfoMap) isNotShadowedByDeeperNodeModulesPackage(info *SymbolExportInfo, packageName string) bool { if packageName == "" || info.moduleFileName == "" { return true } @@ -259,7 +259,7 @@ func (e *exportInfoMap) isNotShadowedByDeeperNodeModulesPackage(info *SymbolExpo return !ok || strings.HasPrefix(info.moduleFileName, packageDeepestNodeModulesPath) } -func (e *exportInfoMap) rehydrateCachedInfo(ch *checker.Checker, info *CachedSymbolExportInfo) *SymbolExportInfo { +func (e *ExportInfoMap) rehydrateCachedInfo(ch *checker.Checker, info *CachedSymbolExportInfo) *SymbolExportInfo { if info.symbol != nil && info.moduleSymbol != nil { return &SymbolExportInfo{ symbol: info.symbol, @@ -374,8 +374,8 @@ func (l *LanguageService) getImportCompletionAction( return fix.moduleSpecifier, l.codeActionForFix(ctx, sourceFile, symbolName, fix /*includeSymbolNameInDescription*/, false) } -func NewExportInfoMap(globalsTypingCacheLocation string) *exportInfoMap { - return &exportInfoMap{ +func NewExportInfoMap(globalsTypingCacheLocation string) *ExportInfoMap { + return &ExportInfoMap{ packages: map[string]string{}, symbols: map[int]symbolExportEntry{}, exportInfo: collections.OrderedMap[ExportInfoMapKey, []*CachedSymbolExportInfo]{}, diff --git a/internal/ls/completions.go b/internal/ls/completions.go index 5a63be9df5..546372a032 100644 --- a/internal/ls/completions.go +++ b/internal/ls/completions.go @@ -86,7 +86,7 @@ type completionDataData struct { keywordFilters KeywordCompletionFilters literals []literalValue symbolToOriginInfoMap map[int]*symbolOriginInfo - symbolToSortTextMap map[ast.SymbolId]sortText + symbolToSortTextMap map[ast.SymbolId]SortText recommendedCompletion *ast.Symbol previousToken *ast.Node contextToken *ast.Node @@ -177,25 +177,25 @@ var noCommaCommitCharacters = []string{".", ";"} var emptyCommitCharacters = []string{} -type sortText string +type SortText string const ( - SortTextLocalDeclarationPriority sortText = "10" - SortTextLocationPriority sortText = "11" - SortTextOptionalMember sortText = "12" - SortTextMemberDeclaredBySpreadAssignment sortText = "13" - SortTextSuggestedClassMembers sortText = "14" - SortTextGlobalsOrKeywords sortText = "15" - SortTextAutoImportSuggestions sortText = "16" - SortTextClassMemberSnippets sortText = "17" - SortTextJavascriptIdentifiers sortText = "18" + SortTextLocalDeclarationPriority SortText = "10" + SortTextLocationPriority SortText = "11" + SortTextOptionalMember SortText = "12" + SortTextMemberDeclaredBySpreadAssignment SortText = "13" + SortTextSuggestedClassMembers SortText = "14" + SortTextGlobalsOrKeywords SortText = "15" + SortTextAutoImportSuggestions SortText = "16" + SortTextClassMemberSnippets SortText = "17" + SortTextJavascriptIdentifiers SortText = "18" ) -func DeprecateSortText(original sortText) sortText { +func DeprecateSortText(original SortText) SortText { return "z" + original } -func sortBelow(original sortText) sortText { +func sortBelow(original SortText) SortText { return original + "1" } @@ -709,7 +709,7 @@ func (l *LanguageService) getCompletionData( var symbols []*ast.Symbol // Keys are indexes of `symbols`. symbolToOriginInfoMap := map[int]*symbolOriginInfo{} - symbolToSortTextMap := map[ast.SymbolId]sortText{} + symbolToSortTextMap := map[ast.SymbolId]SortText{} var seenPropertySymbols collections.Set[ast.SymbolId] importSpecifierResolver := &importSpecifierResolverForCompletions{SourceFile: file, UserPreferences: preferences, l: l} isTypeOnlyLocation := insideJSDocTagTypeExpression || insideJsDocImportTag || @@ -1974,7 +1974,7 @@ func (l *LanguageService) getCompletionEntriesFromSymbols( originalSortText = SortTextLocationPriority } - var sortText sortText + var sortText SortText if isDeprecated(symbol, typeChecker) { sortText = DeprecateSortText(originalSortText) } else { @@ -2050,7 +2050,7 @@ func (l *LanguageService) createCompletionItem( ctx context.Context, typeChecker *checker.Checker, symbol *ast.Symbol, - sortText sortText, + sortText SortText, replacementToken *ast.Node, data *completionDataData, position int, @@ -4494,7 +4494,7 @@ func (l *LanguageService) createLSPCompletionItem( name string, insertText string, filterText string, - sortText sortText, + sortText SortText, elementKind ScriptElementKind, kindModifiers collections.Set[ScriptElementKindModifier], replacementSpan *lsproto.Range, diff --git a/internal/ls/documenthighlights.go b/internal/ls/documenthighlights.go index 65d7039666..7c4f6aa224 100644 --- a/internal/ls/documenthighlights.go +++ b/internal/ls/documenthighlights.go @@ -69,7 +69,7 @@ func (l *LanguageService) getSemanticDocumentHighlights(ctx context.Context, pos return highlights } -func (l *LanguageService) toDocumentHighlight(entry *referenceEntry) (string, *lsproto.DocumentHighlight) { +func (l *LanguageService) toDocumentHighlight(entry *ReferenceEntry) (string, *lsproto.DocumentHighlight) { entry = l.resolveEntry(entry) kind := lsproto.DocumentHighlightKindRead diff --git a/internal/ls/findallreferences.go b/internal/ls/findallreferences.go index e5df1d9d9d..218e20a2f3 100644 --- a/internal/ls/findallreferences.go +++ b/internal/ls/findallreferences.go @@ -51,10 +51,10 @@ type refInfo struct { type SymbolAndEntries struct { definition *Definition - references []*referenceEntry + references []*ReferenceEntry } -func NewSymbolAndEntries(kind definitionKind, node *ast.Node, symbol *ast.Symbol, references []*referenceEntry) *SymbolAndEntries { +func NewSymbolAndEntries(kind DefinitionKind, node *ast.Node, symbol *ast.Symbol, references []*ReferenceEntry) *SymbolAndEntries { return &SymbolAndEntries{ &Definition{ Kind: kind, @@ -65,19 +65,19 @@ func NewSymbolAndEntries(kind definitionKind, node *ast.Node, symbol *ast.Symbol } } -type definitionKind int +type DefinitionKind int const ( - definitionKindSymbol definitionKind = 0 - definitionKindLabel definitionKind = 1 - definitionKindKeyword definitionKind = 2 - definitionKindThis definitionKind = 3 - definitionKindString definitionKind = 4 - definitionKindTripleSlashReference definitionKind = 5 + definitionKindSymbol DefinitionKind = 0 + definitionKindLabel DefinitionKind = 1 + definitionKindKeyword DefinitionKind = 2 + definitionKindThis DefinitionKind = 3 + definitionKindString DefinitionKind = 4 + definitionKindTripleSlashReference DefinitionKind = 5 ) type Definition struct { - Kind definitionKind + Kind DefinitionKind symbol *ast.Symbol node *ast.Node tripleSlashFileRef *tripleSlashDefinition @@ -98,7 +98,7 @@ const ( entryKindSearchedPropertyFoundLocal entryKind = 5 ) -type referenceEntry struct { +type ReferenceEntry struct { kind entryKind node *ast.Node context *ast.Node // !!! ContextWithStartAndEndNode, optional @@ -106,15 +106,15 @@ type referenceEntry struct { textRange *lsproto.Range } -func (l *LanguageService) getRangeOfEntry(entry *referenceEntry) *lsproto.Range { +func (l *LanguageService) getRangeOfEntry(entry *ReferenceEntry) *lsproto.Range { return l.resolveEntry(entry).textRange } -func (l *LanguageService) getFileNameOfEntry(entry *referenceEntry) string { +func (l *LanguageService) getFileNameOfEntry(entry *ReferenceEntry) string { return l.resolveEntry(entry).fileName } -func (l *LanguageService) resolveEntry(entry *referenceEntry) *referenceEntry { +func (l *LanguageService) resolveEntry(entry *ReferenceEntry) *ReferenceEntry { if entry.textRange == nil { sourceFile := ast.GetSourceFileOfNode(entry.node) entry.textRange = l.getRangeOfNode(entry.node, sourceFile, nil /*endNode*/) @@ -123,24 +123,24 @@ func (l *LanguageService) resolveEntry(entry *referenceEntry) *referenceEntry { return entry } -func (l *LanguageService) newRangeEntry(file *ast.SourceFile, start, end int) *referenceEntry { +func (l *LanguageService) newRangeEntry(file *ast.SourceFile, start, end int) *ReferenceEntry { // !!! used in not-yet implemented features - return &referenceEntry{ + return &ReferenceEntry{ kind: entryKindRange, fileName: file.FileName(), textRange: l.createLspRangeFromBounds(start, end, file), } } -func newNodeEntryWithKind(node *ast.Node, kind entryKind) *referenceEntry { +func newNodeEntryWithKind(node *ast.Node, kind entryKind) *ReferenceEntry { e := newNodeEntry(node) e.kind = kind return e } -func newNodeEntry(node *ast.Node) *referenceEntry { +func newNodeEntry(node *ast.Node) *ReferenceEntry { // creates nodeEntry with `kind == entryKindNode` - return &referenceEntry{ + return &ReferenceEntry{ kind: entryKindNode, node: core.OrElse(node.Name(), node), context: getContextNodeForNodeEntry(node), @@ -426,7 +426,7 @@ func (l *LanguageService) ProvideImplementations(ctx context.Context, params *ls node := astnav.GetTouchingPropertyName(sourceFile, position) var seenNodes collections.Set[*ast.Node] - var entries []*referenceEntry + var entries []*ReferenceEntry queue := l.getImplementationReferenceEntries(ctx, program, node, position) for len(queue) != 0 { if ctx.Err() != nil { @@ -446,10 +446,10 @@ func (l *LanguageService) ProvideImplementations(ctx context.Context, params *ls return lsproto.LocationOrLocationsOrDefinitionLinksOrNull{Locations: &locations}, nil } -func (l *LanguageService) getImplementationReferenceEntries(ctx context.Context, program *compiler.Program, node *ast.Node, position int) []*referenceEntry { +func (l *LanguageService) getImplementationReferenceEntries(ctx context.Context, program *compiler.Program, node *ast.Node, position int) []*ReferenceEntry { options := refOptions{use: referenceUseReferences, implementations: true} symbolsAndEntries := l.getReferencedSymbolsForNode(ctx, position, node, program, program.GetSourceFiles(), options, nil) - return core.FlatMap(symbolsAndEntries, func(s *SymbolAndEntries) []*referenceEntry { return s.references }) + return core.FlatMap(symbolsAndEntries, func(s *SymbolAndEntries) []*ReferenceEntry { return s.references }) } func (l *LanguageService) ProvideRename(ctx context.Context, params *lsproto.RenameParams) (lsproto.WorkspaceEditOrNull, error) { @@ -461,7 +461,7 @@ func (l *LanguageService) ProvideRename(ctx context.Context, params *lsproto.Ren } options := refOptions{use: referenceUseRename, useAliasesForRename: true} symbolsAndEntries := l.getReferencedSymbolsForNode(ctx, position, node, program, program.GetSourceFiles(), options, nil) - entries := core.FlatMap(symbolsAndEntries, func(s *SymbolAndEntries) []*referenceEntry { return s.references }) + entries := core.FlatMap(symbolsAndEntries, func(s *SymbolAndEntries) []*ReferenceEntry { return s.references }) changes := make(map[lsproto.DocumentUri][]*lsproto.TextEdit) checker, done := program.GetTypeChecker(ctx) defer done() @@ -480,7 +480,7 @@ func (l *LanguageService) ProvideRename(ctx context.Context, params *lsproto.Ren }, nil } -func (l *LanguageService) getTextForRename(originalNode *ast.Node, entry *referenceEntry, newText string, checker *checker.Checker) string { +func (l *LanguageService) getTextForRename(originalNode *ast.Node, entry *ReferenceEntry, newText string, checker *checker.Checker) string { if entry.kind != entryKindRange && (ast.IsIdentifier(originalNode) || ast.IsStringLiteralLike(originalNode)) { node := entry.node kind := entry.kind @@ -533,7 +533,7 @@ func (l *LanguageService) convertSymbolAndEntriesToLocations(s *SymbolAndEntries return l.convertEntriesToLocations(s.references) } -func (l *LanguageService) convertEntriesToLocations(entries []*referenceEntry) []lsproto.Location { +func (l *LanguageService) convertEntriesToLocations(entries []*ReferenceEntry) []lsproto.Location { locations := make([]lsproto.Location, len(entries)) for i, entry := range entries { locations[i] = lsproto.Location{ @@ -546,7 +546,7 @@ func (l *LanguageService) convertEntriesToLocations(entries []*referenceEntry) [ func (l *LanguageService) mergeReferences(program *compiler.Program, referencesToMerge ...[]*SymbolAndEntries) []*SymbolAndEntries { result := []*SymbolAndEntries{} - getSourceFileIndexOfEntry := func(program *compiler.Program, entry *referenceEntry) int { + getSourceFileIndexOfEntry := func(program *compiler.Program, entry *ReferenceEntry) int { var sourceFile *ast.SourceFile if entry.kind == entryKindRange { sourceFile = program.GetSourceFile(entry.fileName) @@ -582,7 +582,7 @@ func (l *LanguageService) mergeReferences(program *compiler.Program, referencesT reference := result[refIndex] sortedRefs := append(reference.references, entry.references...) - slices.SortStableFunc(sortedRefs, func(entry1, entry2 *referenceEntry) int { + slices.SortStableFunc(sortedRefs, func(entry1, entry2 *ReferenceEntry) int { entry1File := getSourceFileIndexOfEntry(program, entry1) entry2File := getSourceFileIndexOfEntry(program, entry2) if entry1File != entry2File { @@ -735,7 +735,7 @@ func getReferencedSymbolsSpecial(node *ast.Node, sourceFiles []*ast.SourceFile) } if node.Kind == ast.KindStaticKeyword && node.Parent.Kind == ast.KindClassStaticBlockDeclaration { - return []*SymbolAndEntries{{definition: &Definition{Kind: definitionKindKeyword, node: node}, references: []*referenceEntry{newNodeEntry(node)}}} + return []*SymbolAndEntries{{definition: &Definition{Kind: definitionKindKeyword, node: node}, references: []*ReferenceEntry{newNodeEntry(node)}}} } // Labels @@ -767,7 +767,7 @@ func getReferencedSymbolsSpecial(node *ast.Node, sourceFiles []*ast.SourceFile) func getLabelReferencesInNode(container *ast.Node, targetLabel *ast.Node) []*SymbolAndEntries { sourceFile := ast.GetSourceFileOfNode(container) labelName := targetLabel.Text() - references := core.MapNonNil(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), func(node *ast.Node) *referenceEntry { + references := core.MapNonNil(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), func(node *ast.Node) *ReferenceEntry { // Only pick labels that are either the target label, or have a target that is the target label if node == targetLabel.AsNode() || (isJumpStatementTarget(node) && getTargetLabel(node, labelName) == targetLabel) { return newNodeEntry(node) @@ -839,10 +839,10 @@ func getReferencesForThisKeyword(thisOrSuperKeyword *ast.Node, sourceFiles []*as return false }) }), - func(n *ast.Node) *referenceEntry { return newNodeEntry(n) }, + func(n *ast.Node) *ReferenceEntry { return newNodeEntry(n) }, ) - thisParameter := core.FirstNonNil(references, func(ref *referenceEntry) *ast.Node { + thisParameter := core.FirstNonNil(references, func(ref *ReferenceEntry) *ast.Node { if ref.node.Parent.Kind == ast.KindParameter { return ref.node } @@ -871,7 +871,7 @@ func getReferencesForSuperKeyword(superKeyword *ast.Node) []*SymbolAndEntries { } sourceFile := ast.GetSourceFileOfNode(searchSpaceNode) - references := core.MapNonNil(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), func(node *ast.Node) *referenceEntry { + references := core.MapNonNil(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), func(node *ast.Node) *ReferenceEntry { if node.Kind != ast.KindSuperKeyword { return nil } @@ -891,8 +891,8 @@ 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 { + 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 if ast.IsImportMeta(parent) { return newNodeEntry(parent) @@ -908,9 +908,9 @@ func getAllReferencesForImportMeta(sourceFiles []*ast.SourceFile) []*SymbolAndEn func getAllReferencesForKeyword(sourceFiles []*ast.SourceFile, keywordKind ast.Kind, filterReadOnlyTypeOperator bool) []*SymbolAndEntries { // references is a list of NodeEntry - references := core.FlatMap(sourceFiles, func(sourceFile *ast.SourceFile) []*referenceEntry { + references := core.FlatMap(sourceFiles, func(sourceFile *ast.SourceFile) []*ReferenceEntry { // cancellationToken.throwIfCancellationRequested(); - return core.MapNonNil(getPossibleSymbolReferenceNodes(sourceFile, scanner.TokenToString(keywordKind), sourceFile.AsNode()), func(referenceLocation *ast.Node) *referenceEntry { + return core.MapNonNil(getPossibleSymbolReferenceNodes(sourceFile, scanner.TokenToString(keywordKind), sourceFile.AsNode()), func(referenceLocation *ast.Node) *ReferenceEntry { if referenceLocation.Kind == keywordKind && (!filterReadOnlyTypeOperator || isReadonlyTypeOperator(referenceLocation)) { return newNodeEntry(referenceLocation) } @@ -1004,9 +1004,9 @@ func findFirstJsxNode(root *ast.Node) *ast.Node { return visit(root) } -func getReferencesForNonModule(referencedFile *ast.SourceFile, program *compiler.Program) []*referenceEntry { +func getReferencesForNonModule(referencedFile *ast.SourceFile, program *compiler.Program) []*ReferenceEntry { // !!! not implemented - return []*referenceEntry{} + return []*ReferenceEntry{} } func getMergedAliasedSymbolOfNamespaceExportDeclaration(node *ast.Node, symbol *ast.Symbol, checker *checker.Checker) *ast.Symbol { @@ -1028,7 +1028,7 @@ func (l *LanguageService) getReferencedSymbolsForModule(ctx context.Context, pro defer done() moduleRefs := findModuleReferences(program, sourceFiles, symbol, checker) - references := core.MapNonNil(moduleRefs, func(reference ModuleReference) *referenceEntry { + references := core.MapNonNil(moduleRefs, func(reference ModuleReference) *ReferenceEntry { switch reference.kind { case ModuleReferenceKindImport: parent := reference.literal.Parent @@ -1062,7 +1062,7 @@ func (l *LanguageService) getReferencedSymbolsForModule(ctx context.Context, pro } return newNodeEntry(rangeNode) case ModuleReferenceKindReference: - return &referenceEntry{ + return &ReferenceEntry{ kind: entryKindRange, fileName: reference.referencingFile.FileName(), textRange: l.createLspRangeFromBounds(reference.ref.Pos(), reference.ref.End(), reference.referencingFile), diff --git a/internal/pprof/pprof.go b/internal/pprof/pprof.go index 23692f4dbf..2523c94885 100644 --- a/internal/pprof/pprof.go +++ b/internal/pprof/pprof.go @@ -8,7 +8,7 @@ import ( "runtime/pprof" ) -type profileSession struct { +type ProfileSession struct { cpuFilePath string memFilePath string cpuFile *os.File @@ -17,7 +17,7 @@ type profileSession struct { } // BeginProfiling starts CPU and memory profiling, writing the profiles to the specified directory. -func BeginProfiling(profileDir string, logWriter io.Writer) *profileSession { +func BeginProfiling(profileDir string, logWriter io.Writer) *ProfileSession { if err := os.MkdirAll(profileDir, 0o755); err != nil { panic(err) } @@ -39,7 +39,7 @@ func BeginProfiling(profileDir string, logWriter io.Writer) *profileSession { panic(err) } - return &profileSession{ + return &ProfileSession{ cpuFilePath: cpuProfilePath, memFilePath: memProfilePath, cpuFile: cpuFile, @@ -48,7 +48,7 @@ func BeginProfiling(profileDir string, logWriter io.Writer) *profileSession { } } -func (p *profileSession) Stop() { +func (p *ProfileSession) Stop() { pprof.StopCPUProfile() err := pprof.Lookup("allocs").WriteTo(p.memFile, 0) if err != nil { diff --git a/internal/project/checkerpool.go b/internal/project/checkerpool.go index 6bcbcc686d..017fd2fbee 100644 --- a/internal/project/checkerpool.go +++ b/internal/project/checkerpool.go @@ -12,7 +12,7 @@ import ( "github.com/microsoft/typescript-go/internal/core" ) -type checkerPool struct { +type CheckerPool struct { maxCheckers int program *compiler.Program @@ -26,10 +26,10 @@ type checkerPool struct { log func(msg string) } -var _ compiler.CheckerPool = (*checkerPool)(nil) +var _ compiler.CheckerPool = (*CheckerPool)(nil) -func newCheckerPool(maxCheckers int, program *compiler.Program, log func(msg string)) *checkerPool { - pool := &checkerPool{ +func newCheckerPool(maxCheckers int, program *compiler.Program, log func(msg string)) *CheckerPool { + pool := &CheckerPool{ program: program, maxCheckers: maxCheckers, checkers: make([]*checker.Checker, maxCheckers), @@ -42,7 +42,7 @@ func newCheckerPool(maxCheckers int, program *compiler.Program, log func(msg str return pool } -func (p *checkerPool) GetCheckerForFile(ctx context.Context, file *ast.SourceFile) (*checker.Checker, func()) { +func (p *CheckerPool) GetCheckerForFile(ctx context.Context, file *ast.SourceFile) (*checker.Checker, func()) { p.mu.Lock() defer p.mu.Unlock() @@ -75,18 +75,18 @@ func (p *checkerPool) GetCheckerForFile(ctx context.Context, file *ast.SourceFil return checker, p.createRelease(requestID, index, checker) } -func (p *checkerPool) GetChecker(ctx context.Context) (*checker.Checker, func()) { +func (p *CheckerPool) GetChecker(ctx context.Context) (*checker.Checker, func()) { p.mu.Lock() defer p.mu.Unlock() checker, index := p.getCheckerLocked(core.GetRequestID(ctx)) return checker, p.createRelease(core.GetRequestID(ctx), index, checker) } -func (p *checkerPool) Files(checker *checker.Checker) iter.Seq[*ast.SourceFile] { +func (p *CheckerPool) Files(checker *checker.Checker) iter.Seq[*ast.SourceFile] { panic("unimplemented") } -func (p *checkerPool) GetAllCheckers(ctx context.Context) ([]*checker.Checker, func()) { +func (p *CheckerPool) GetAllCheckers(ctx context.Context) ([]*checker.Checker, func()) { p.mu.Lock() defer p.mu.Unlock() @@ -104,7 +104,7 @@ func (p *checkerPool) GetAllCheckers(ctx context.Context) ([]*checker.Checker, f return []*checker.Checker{c}, release } -func (p *checkerPool) getCheckerLocked(requestID string) (*checker.Checker, int) { +func (p *CheckerPool) getCheckerLocked(requestID string) (*checker.Checker, int) { if checker, index := p.getImmediatelyAvailableChecker(); checker != nil { p.inUse[checker] = true if requestID != "" { @@ -130,7 +130,7 @@ func (p *checkerPool) getCheckerLocked(requestID string) (*checker.Checker, int) return checker, index } -func (p *checkerPool) getRequestCheckerLocked(requestID string) (*checker.Checker, func()) { +func (p *CheckerPool) getRequestCheckerLocked(requestID string) (*checker.Checker, func()) { if index, ok := p.requestAssociations[requestID]; ok { checker := p.checkers[index] if checker != nil { @@ -146,7 +146,7 @@ func (p *checkerPool) getRequestCheckerLocked(requestID string) (*checker.Checke return nil, noop } -func (p *checkerPool) getImmediatelyAvailableChecker() (*checker.Checker, int) { +func (p *CheckerPool) getImmediatelyAvailableChecker() (*checker.Checker, int) { for i, checker := range p.checkers { if checker == nil { continue @@ -159,7 +159,7 @@ func (p *checkerPool) getImmediatelyAvailableChecker() (*checker.Checker, int) { return nil, -1 } -func (p *checkerPool) waitForAvailableChecker() (*checker.Checker, int) { +func (p *CheckerPool) waitForAvailableChecker() (*checker.Checker, int) { p.log("checkerpool: Waiting for an available checker") for { p.cond.Wait() @@ -170,7 +170,7 @@ func (p *checkerPool) waitForAvailableChecker() (*checker.Checker, int) { } } -func (p *checkerPool) createRelease(requestId string, index int, checker *checker.Checker) func() { +func (p *CheckerPool) createRelease(requestId string, index int, checker *checker.Checker) func() { return func() { p.mu.Lock() defer p.mu.Unlock() @@ -188,7 +188,7 @@ func (p *checkerPool) createRelease(requestId string, index int, checker *checke } } -func (p *checkerPool) isFullLocked() bool { +func (p *CheckerPool) isFullLocked() bool { for _, checker := range p.checkers { if checker == nil { return false @@ -197,7 +197,7 @@ func (p *checkerPool) isFullLocked() bool { return true } -func (p *checkerPool) createCheckerLocked() (*checker.Checker, int) { +func (p *CheckerPool) createCheckerLocked() (*checker.Checker, int) { for i, existing := range p.checkers { if existing == nil { checker := checker.NewChecker(p.program) @@ -208,7 +208,7 @@ func (p *checkerPool) createCheckerLocked() (*checker.Checker, int) { panic("called createCheckerLocked when pool is full") } -func (p *checkerPool) isRequestCheckerInUse(requestID string) bool { +func (p *CheckerPool) isRequestCheckerInUse(requestID string) bool { p.mu.Lock() defer p.mu.Unlock() @@ -221,7 +221,7 @@ func (p *checkerPool) isRequestCheckerInUse(requestID string) bool { return false } -func (p *checkerPool) size() int { +func (p *CheckerPool) size() int { p.mu.Lock() defer p.mu.Unlock() size := 0 diff --git a/internal/project/compilerhost.go b/internal/project/compilerhost.go index d58b3522b8..c6293c701c 100644 --- a/internal/project/compilerhost.go +++ b/internal/project/compilerhost.go @@ -25,7 +25,7 @@ type compilerHost struct { seenFiles *collections.SyncSet[tspath.Path] project *Project - builder *projectCollectionBuilder + builder *ProjectCollectionBuilder logger *logging.LogTree } @@ -47,7 +47,7 @@ func (c *builderFileSource) FS() vfs.FS { func newCompilerHost( currentDirectory string, project *Project, - builder *projectCollectionBuilder, + builder *ProjectCollectionBuilder, logger *logging.LogTree, ) *compilerHost { seenFiles := &collections.SyncSet[tspath.Path]{} @@ -75,7 +75,7 @@ func newCompilerHost( // freeze clears references to mutable state to make the compilerHost safe for use // after the snapshot has been finalized. See the usage in snapshot.go for more details. -func (c *compilerHost) freeze(snapshotFS *snapshotFS, configFileRegistry *ConfigFileRegistry) { +func (c *compilerHost) freeze(snapshotFS *SnapshotFS, configFileRegistry *ConfigFileRegistry) { if c.builder == nil { panic("freeze can only be called once") } diff --git a/internal/project/configfileregistry.go b/internal/project/configfileregistry.go index 1b6613a613..000decbd3e 100644 --- a/internal/project/configfileregistry.go +++ b/internal/project/configfileregistry.go @@ -42,7 +42,7 @@ type configFileEntry struct { // when this is set, no other fields will be used. retainingConfigs map[tspath.Path]struct{} // rootFilesWatch is a watch for the root files of this config file. - rootFilesWatch *WatchedFiles[patternsAndIgnored] + rootFilesWatch *WatchedFiles[PatternsAndIgnored] } func newConfigFileEntry(fileName string) *configFileEntry { diff --git a/internal/project/configfileregistrybuilder.go b/internal/project/configfileregistrybuilder.go index c8fc308500..6dbb3c5f34 100644 --- a/internal/project/configfileregistrybuilder.go +++ b/internal/project/configfileregistrybuilder.go @@ -25,7 +25,7 @@ var ( // all changes have been made. type configFileRegistryBuilder struct { fs *snapshotFSBuilder - extendedConfigCache *extendedConfigCache + extendedConfigCache *ExtendedConfigCache sessionOptions *SessionOptions base *ConfigFileRegistry @@ -36,7 +36,7 @@ type configFileRegistryBuilder struct { func newConfigFileRegistryBuilder( fs *snapshotFSBuilder, oldConfigFileRegistry *ConfigFileRegistry, - extendedConfigCache *extendedConfigCache, + extendedConfigCache *ExtendedConfigCache, sessionOptions *SessionOptions, logger *logging.LogTree, ) *configFileRegistryBuilder { @@ -216,7 +216,7 @@ func (c *configFileRegistryBuilder) updateRootFilesWatch(fileName string, entry } slices.Sort(globs) - entry.rootFilesWatch = entry.rootFilesWatch.Clone(patternsAndIgnored{ + entry.rootFilesWatch = entry.rootFilesWatch.Clone(PatternsAndIgnored{ patterns: globs, ignored: ignored, }) diff --git a/internal/project/extendedconfigcache.go b/internal/project/extendedconfigcache.go index 38654c55ae..bf4e627587 100644 --- a/internal/project/extendedconfigcache.go +++ b/internal/project/extendedconfigcache.go @@ -9,7 +9,7 @@ import ( "github.com/zeebo/xxh3" ) -type extendedConfigCache struct { +type ExtendedConfigCache struct { entries collections.SyncMap[tspath.Path, *extendedConfigCacheEntry] } @@ -20,7 +20,7 @@ type extendedConfigCacheEntry struct { refCount int } -func (c *extendedConfigCache) Acquire(fh FileHandle, path tspath.Path, parse func() *tsoptions.ExtendedConfigCacheEntry) *tsoptions.ExtendedConfigCacheEntry { +func (c *ExtendedConfigCache) Acquire(fh FileHandle, path tspath.Path, parse func() *tsoptions.ExtendedConfigCacheEntry) *tsoptions.ExtendedConfigCacheEntry { entry, loaded := c.loadOrStoreNewLockedEntry(path) defer entry.mu.Unlock() var hash xxh3.Uint128 @@ -35,7 +35,7 @@ func (c *extendedConfigCache) Acquire(fh FileHandle, path tspath.Path, parse fun return entry.entry } -func (c *extendedConfigCache) Ref(path tspath.Path) { +func (c *ExtendedConfigCache) Ref(path tspath.Path) { if entry, ok := c.entries.Load(path); ok { entry.mu.Lock() entry.refCount++ @@ -43,7 +43,7 @@ func (c *extendedConfigCache) Ref(path tspath.Path) { } } -func (c *extendedConfigCache) Deref(path tspath.Path) { +func (c *ExtendedConfigCache) Deref(path tspath.Path) { if entry, ok := c.entries.Load(path); ok { entry.mu.Lock() entry.refCount-- @@ -55,7 +55,7 @@ func (c *extendedConfigCache) Deref(path tspath.Path) { } } -func (c *extendedConfigCache) Has(path tspath.Path) bool { +func (c *ExtendedConfigCache) Has(path tspath.Path) bool { _, ok := c.entries.Load(path) return ok } @@ -63,7 +63,7 @@ func (c *extendedConfigCache) Has(path tspath.Path) bool { // loadOrStoreNewLockedEntry loads an existing entry or creates a new one. The returned // entry's mutex is locked and its refCount is incremented (or initialized to 1 // in the case of a new entry). -func (c *extendedConfigCache) loadOrStoreNewLockedEntry(path tspath.Path) (*extendedConfigCacheEntry, bool) { +func (c *ExtendedConfigCache) loadOrStoreNewLockedEntry(path tspath.Path) (*extendedConfigCacheEntry, bool) { entry := &extendedConfigCacheEntry{refCount: 1} entry.mu.Lock() if existing, loaded := c.entries.LoadOrStore(path, entry); loaded { diff --git a/internal/project/overlayfs.go b/internal/project/overlayfs.go index 26c6e2aa68..bed8a8459a 100644 --- a/internal/project/overlayfs.go +++ b/internal/project/overlayfs.go @@ -111,17 +111,17 @@ func (f *diskFile) Clone() *diskFile { } } -var _ FileHandle = (*overlay)(nil) +var _ FileHandle = (*Overlay)(nil) -type overlay struct { +type Overlay struct { fileBase version int32 kind core.ScriptKind matchesDiskText bool } -func newOverlay(fileName string, content string, version int32, kind core.ScriptKind) *overlay { - return &overlay{ +func newOverlay(fileName string, content string, version int32, kind core.ScriptKind) *Overlay { + return &Overlay{ fileBase: fileBase{ fileName: fileName, content: content, @@ -132,21 +132,21 @@ func newOverlay(fileName string, content string, version int32, kind core.Script } } -func (o *overlay) Version() int32 { +func (o *Overlay) Version() int32 { return o.version } -func (o *overlay) Text() string { +func (o *Overlay) Text() string { return o.content } // MatchesDiskText may return false negatives, but never false positives. -func (o *overlay) MatchesDiskText() bool { +func (o *Overlay) MatchesDiskText() bool { return o.matchesDiskText } // !!! optimization: incorporate mtime -func (o *overlay) computeMatchesDiskText(fs vfs.FS) bool { +func (o *Overlay) computeMatchesDiskText(fs vfs.FS) bool { if isDynamicFileName(o.fileName) { return false } @@ -157,11 +157,11 @@ func (o *overlay) computeMatchesDiskText(fs vfs.FS) bool { return xxh3.Hash128([]byte(diskContent)) == o.hash } -func (o *overlay) IsOverlay() bool { +func (o *Overlay) IsOverlay() bool { return true } -func (o *overlay) Kind() core.ScriptKind { +func (o *Overlay) Kind() core.ScriptKind { return o.kind } @@ -171,10 +171,10 @@ type overlayFS struct { positionEncoding lsproto.PositionEncodingKind mu sync.RWMutex - overlays map[tspath.Path]*overlay + overlays map[tspath.Path]*Overlay } -func newOverlayFS(fs vfs.FS, overlays map[tspath.Path]*overlay, positionEncoding lsproto.PositionEncodingKind, toPath func(string) tspath.Path) *overlayFS { +func newOverlayFS(fs vfs.FS, overlays map[tspath.Path]*Overlay, positionEncoding lsproto.PositionEncodingKind, toPath func(string) tspath.Path) *overlayFS { return &overlayFS{ fs: fs, positionEncoding: positionEncoding, @@ -183,7 +183,7 @@ func newOverlayFS(fs vfs.FS, overlays map[tspath.Path]*overlay, positionEncoding } } -func (fs *overlayFS) Overlays() map[tspath.Path]*overlay { +func (fs *overlayFS) Overlays() map[tspath.Path]*Overlay { fs.mu.RLock() defer fs.mu.RUnlock() return fs.overlays @@ -206,7 +206,7 @@ func (fs *overlayFS) getFile(fileName string) FileHandle { return newDiskFile(fileName, content) } -func (fs *overlayFS) processChanges(changes []FileChange) (FileChangeSummary, map[tspath.Path]*overlay) { +func (fs *overlayFS) processChanges(changes []FileChange) (FileChangeSummary, map[tspath.Path]*Overlay) { fs.mu.Lock() defer fs.mu.Unlock() diff --git a/internal/project/overlayfs_test.go b/internal/project/overlayfs_test.go index 5f044bcacd..cb297f464a 100644 --- a/internal/project/overlayfs_test.go +++ b/internal/project/overlayfs_test.go @@ -19,7 +19,7 @@ func TestProcessChanges(t *testing.T) { }, false /* useCaseSensitiveFileNames */) return newOverlayFS( testFS, - make(map[tspath.Path]*overlay), + make(map[tspath.Path]*Overlay), lsproto.PositionEncodingKindUTF16, func(fileName string) tspath.Path { return tspath.Path(fileName) diff --git a/internal/project/project.go b/internal/project/project.go index 386cc2f4be..77a99abf06 100644 --- a/internal/project/project.go +++ b/internal/project/project.go @@ -69,12 +69,12 @@ type Project struct { // The ID of the snapshot that created the program stored in this project. ProgramLastUpdate uint64 - programFilesWatch *WatchedFiles[patternsAndIgnored] + programFilesWatch *WatchedFiles[PatternsAndIgnored] failedLookupsWatch *WatchedFiles[map[tspath.Path]string] affectingLocationsWatch *WatchedFiles[map[tspath.Path]string] - typingsWatch *WatchedFiles[patternsAndIgnored] + typingsWatch *WatchedFiles[PatternsAndIgnored] - checkerPool *checkerPool + checkerPool *CheckerPool // installedTypingsInfo is the value of `project.ComputeTypingsInfo()` that was // used during the most recently completed typings installation. @@ -86,7 +86,7 @@ type Project struct { func NewConfiguredProject( configFileName string, configFilePath tspath.Path, - builder *projectCollectionBuilder, + builder *ProjectCollectionBuilder, logger *logging.LogTree, ) *Project { return NewProject(configFileName, KindConfigured, tspath.GetDirectoryPath(configFileName), builder, logger) @@ -96,7 +96,7 @@ func NewInferredProject( currentDirectory string, compilerOptions *core.CompilerOptions, rootFileNames []string, - builder *projectCollectionBuilder, + builder *ProjectCollectionBuilder, logger *logging.LogTree, ) *Project { p := NewProject(inferredProjectName, KindInferred, currentDirectory, builder, logger) @@ -131,7 +131,7 @@ func NewProject( configFileName string, kind Kind, currentDirectory string, - builder *projectCollectionBuilder, + builder *ProjectCollectionBuilder, logger *logging.LogTree, ) *Project { if logger != nil { @@ -270,13 +270,13 @@ func (p *Project) getCommandLineWithTypingsFiles() *tsoptions.ParsedCommandLine type CreateProgramResult struct { Program *compiler.Program UpdateKind ProgramUpdateKind - CheckerPool *checkerPool + CheckerPool *CheckerPool } func (p *Project) CreateProgram() CreateProgramResult { updateKind := ProgramUpdateKindNewFiles var programCloned bool - var checkerPool *checkerPool + var checkerPool *CheckerPool var newProgram *compiler.Program // Create the command line, potentially augmented with typing files @@ -327,7 +327,7 @@ func (p *Project) CreateProgram() CreateProgramResult { } } -func (p *Project) CloneWatchers(workspaceDir string, libDir string) (programFilesWatch *WatchedFiles[patternsAndIgnored], failedLookupsWatch *WatchedFiles[map[tspath.Path]string], affectingLocationsWatch *WatchedFiles[map[tspath.Path]string]) { +func (p *Project) CloneWatchers(workspaceDir string, libDir string) (programFilesWatch *WatchedFiles[PatternsAndIgnored], failedLookupsWatch *WatchedFiles[map[tspath.Path]string], affectingLocationsWatch *WatchedFiles[map[tspath.Path]string]) { failedLookups := make(map[tspath.Path]string) affectingLocations := make(map[tspath.Path]string) programFiles := getNonRootFileGlobs(workspaceDir, libDir, p.Program.GetSourceFiles(), p.CommandLine.FileNamesByPath(), tspath.ComparePathsOptions{ diff --git a/internal/project/projectcollectionbuilder.go b/internal/project/projectcollectionbuilder.go index c7ed8bd2f9..0aa1da4cf8 100644 --- a/internal/project/projectcollectionbuilder.go +++ b/internal/project/projectcollectionbuilder.go @@ -25,10 +25,10 @@ const ( projectLoadKindCreate ) -type projectCollectionBuilder struct { +type ProjectCollectionBuilder struct { sessionOptions *SessionOptions parseCache *ParseCache - extendedConfigCache *extendedConfigCache + extendedConfigCache *ExtendedConfigCache ctx context.Context fs *snapshotFSBuilder @@ -55,9 +55,9 @@ func newProjectCollectionBuilder( compilerOptionsForInferredProjects *core.CompilerOptions, sessionOptions *SessionOptions, parseCache *ParseCache, - extendedConfigCache *extendedConfigCache, -) *projectCollectionBuilder { - return &projectCollectionBuilder{ + extendedConfigCache *ExtendedConfigCache, +) *ProjectCollectionBuilder { + return &ProjectCollectionBuilder{ ctx: ctx, fs: fs, compilerOptionsForInferredProjects: compilerOptionsForInferredProjects, @@ -73,7 +73,7 @@ func newProjectCollectionBuilder( } } -func (b *projectCollectionBuilder) Finalize(logger *logging.LogTree) (*ProjectCollection, *ConfigFileRegistry) { +func (b *ProjectCollectionBuilder) Finalize(logger *logging.LogTree) (*ProjectCollection, *ConfigFileRegistry) { var changed bool newProjectCollection := b.base ensureCloned := func() { @@ -103,7 +103,7 @@ func (b *projectCollectionBuilder) Finalize(logger *logging.LogTree) (*ProjectCo return newProjectCollection, configFileRegistry } -func (b *projectCollectionBuilder) forEachProject(fn func(entry dirty.Value[*Project]) bool) { +func (b *ProjectCollectionBuilder) forEachProject(fn func(entry dirty.Value[*Project]) bool) { keepGoing := true b.configuredProjects.Range(func(entry *dirty.SyncMapEntry[tspath.Path, *Project]) bool { keepGoing = fn(entry) @@ -117,7 +117,7 @@ func (b *projectCollectionBuilder) forEachProject(fn func(entry dirty.Value[*Pro } } -func (b *projectCollectionBuilder) HandleAPIRequest(apiRequest *APISnapshotRequest, logger *logging.LogTree) error { +func (b *ProjectCollectionBuilder) HandleAPIRequest(apiRequest *APISnapshotRequest, logger *logging.LogTree) error { var projectsToClose map[tspath.Path]struct{} if apiRequest.CloseProjects != nil { projectsToClose = maps.Clone(apiRequest.CloseProjects.M) @@ -166,7 +166,7 @@ func (b *projectCollectionBuilder) HandleAPIRequest(apiRequest *APISnapshotReque return nil } -func (b *projectCollectionBuilder) DidChangeFiles(summary FileChangeSummary, logger *logging.LogTree) { +func (b *ProjectCollectionBuilder) DidChangeFiles(summary FileChangeSummary, logger *logging.LogTree) { changedFiles := make([]tspath.Path, 0, len(summary.Closed)+summary.Changed.Len()) for uri, hash := range summary.Closed { fileName := uri.FileName() @@ -287,7 +287,7 @@ func logChangeFileResult(result changeFileResult, logger *logging.LogTree) { } } -func (b *projectCollectionBuilder) DidRequestFile(uri lsproto.DocumentUri, logger *logging.LogTree) { +func (b *ProjectCollectionBuilder) DidRequestFile(uri lsproto.DocumentUri, logger *logging.LogTree) { startTime := time.Now() fileName := uri.FileName() hasChanges := b.programStructureChanged @@ -338,7 +338,7 @@ func (b *projectCollectionBuilder) DidRequestFile(uri lsproto.DocumentUri, logge } } -func (b *projectCollectionBuilder) DidUpdateATAState(ataChanges map[tspath.Path]*ATAStateChange, logger *logging.LogTree) { +func (b *ProjectCollectionBuilder) DidUpdateATAState(ataChanges map[tspath.Path]*ATAStateChange, logger *logging.LogTree) { updateProject := func(project dirty.Value[*Project], ataChange *ATAStateChange) { project.ChangeIf( func(p *Project) bool { @@ -383,7 +383,7 @@ func (b *projectCollectionBuilder) DidUpdateATAState(ataChanges map[tspath.Path] } } -func (b *projectCollectionBuilder) markProjectsAffectedByConfigChanges( +func (b *ProjectCollectionBuilder) markProjectsAffectedByConfigChanges( configChangeResult changeFileResult, logger *logging.LogTree, ) bool { @@ -415,7 +415,7 @@ func (b *projectCollectionBuilder) markProjectsAffectedByConfigChanges( return hasChanges } -func (b *projectCollectionBuilder) findDefaultProject(fileName string, path tspath.Path) dirty.Value[*Project] { +func (b *ProjectCollectionBuilder) findDefaultProject(fileName string, path tspath.Path) dirty.Value[*Project] { if configuredProject := b.findDefaultConfiguredProject(fileName, path); configuredProject != nil { return configuredProject } @@ -432,7 +432,7 @@ func (b *projectCollectionBuilder) findDefaultProject(fileName string, path tspa return nil } -func (b *projectCollectionBuilder) findDefaultConfiguredProject(fileName string, path tspath.Path) *dirty.SyncMapEntry[tspath.Path, *Project] { +func (b *ProjectCollectionBuilder) findDefaultConfiguredProject(fileName string, path tspath.Path) *dirty.SyncMapEntry[tspath.Path, *Project] { // !!! look in fileDefaultProjects first? // Sort configured projects so we can use a deterministic "first" as a last resort. var configuredProjectPaths []tspath.Path @@ -457,7 +457,7 @@ func (b *projectCollectionBuilder) findDefaultConfiguredProject(fileName string, return configuredProjects[project] } -func (b *projectCollectionBuilder) ensureConfiguredProjectAndAncestorsForOpenFile(fileName string, path tspath.Path, logger *logging.LogTree) searchResult { +func (b *ProjectCollectionBuilder) ensureConfiguredProjectAndAncestorsForOpenFile(fileName string, path tspath.Path, logger *logging.LogTree) searchResult { result := b.findOrCreateDefaultConfiguredProjectForOpenScriptInfo(fileName, path, projectLoadKindCreate, logger) if result.project != nil { // !!! sheetal todo this later @@ -495,7 +495,7 @@ type searchResult struct { retain collections.Set[tspath.Path] } -func (b *projectCollectionBuilder) findOrCreateDefaultConfiguredProjectWorker( +func (b *ProjectCollectionBuilder) findOrCreateDefaultConfiguredProjectWorker( fileName string, path tspath.Path, configFileName string, @@ -653,7 +653,7 @@ func (b *projectCollectionBuilder) findOrCreateDefaultConfiguredProjectWorker( return searchResult{retain: retain} } -func (b *projectCollectionBuilder) findOrCreateDefaultConfiguredProjectForOpenScriptInfo( +func (b *ProjectCollectionBuilder) findOrCreateDefaultConfiguredProjectForOpenScriptInfo( fileName string, path tspath.Path, loadKind projectLoadKind, @@ -697,7 +697,7 @@ func (b *projectCollectionBuilder) findOrCreateDefaultConfiguredProjectForOpenSc return searchResult{} } -func (b *projectCollectionBuilder) findOrCreateProject( +func (b *ProjectCollectionBuilder) findOrCreateProject( configFileName string, configFilePath tspath.Path, loadKind projectLoadKind, @@ -711,11 +711,11 @@ func (b *projectCollectionBuilder) findOrCreateProject( return entry } -func (b *projectCollectionBuilder) toPath(fileName string) tspath.Path { +func (b *ProjectCollectionBuilder) toPath(fileName string) tspath.Path { return tspath.ToPath(fileName, b.sessionOptions.CurrentDirectory, b.fs.fs.UseCaseSensitiveFileNames()) } -func (b *projectCollectionBuilder) updateInferredProjectRoots(rootFileNames []string, logger *logging.LogTree) bool { +func (b *ProjectCollectionBuilder) updateInferredProjectRoots(rootFileNames []string, logger *logging.LogTree) bool { if len(rootFileNames) == 0 { if b.inferredProject.Value() != nil { if logger != nil { @@ -761,7 +761,7 @@ func (b *projectCollectionBuilder) updateInferredProjectRoots(rootFileNames []st // updateProgram updates the program for the given project entry if necessary. It returns // a boolean indicating whether the update could have caused any structure-affecting changes. -func (b *projectCollectionBuilder) updateProgram(entry dirty.Value[*Project], logger *logging.LogTree) bool { +func (b *ProjectCollectionBuilder) updateProgram(entry dirty.Value[*Project], logger *logging.LogTree) bool { var updateProgram bool var filesChanged bool configFileName := entry.Value().configFileName @@ -823,7 +823,7 @@ func (b *projectCollectionBuilder) updateProgram(entry dirty.Value[*Project], lo return filesChanged } -func (b *projectCollectionBuilder) markFilesChanged(entry dirty.Value[*Project], paths []tspath.Path, changeType lsproto.FileChangeType, logger *logging.LogTree) { +func (b *ProjectCollectionBuilder) markFilesChanged(entry dirty.Value[*Project], paths []tspath.Path, changeType lsproto.FileChangeType, logger *logging.LogTree) { var dirty bool var dirtyFilePath tspath.Path entry.ChangeIf( @@ -875,7 +875,7 @@ func (b *projectCollectionBuilder) markFilesChanged(entry dirty.Value[*Project], ) } -func (b *projectCollectionBuilder) deleteConfiguredProject(project dirty.Value[*Project], logger *logging.LogTree) { +func (b *ProjectCollectionBuilder) deleteConfiguredProject(project dirty.Value[*Project], logger *logging.LogTree) { projectPath := project.Value().configFilePath if logger != nil { logger.Log("Deleting configured project: " + project.Value().configFileName) diff --git a/internal/project/session.go b/internal/project/session.go index ce00336111..4742c343e0 100644 --- a/internal/project/session.go +++ b/internal/project/session.go @@ -73,7 +73,7 @@ type Session struct { parseCache *ParseCache // extendedConfigCache is the ref-counted cache of tsconfig ASTs // that are used in the "extends" of another tsconfig. - extendedConfigCache *extendedConfigCache + extendedConfigCache *ExtendedConfigCache // programCounter counts how many snapshots reference a program. // When a program is no longer referenced, its source files are // released from the parseCache. @@ -127,12 +127,12 @@ func NewSession(init *SessionInit) *Session { toPath := func(fileName string) tspath.Path { return tspath.ToPath(fileName, currentDirectory, useCaseSensitiveFileNames) } - overlayFS := newOverlayFS(init.FS, make(map[tspath.Path]*overlay), init.Options.PositionEncoding, toPath) + overlayFS := newOverlayFS(init.FS, make(map[tspath.Path]*Overlay), init.Options.PositionEncoding, toPath) parseCache := init.ParseCache if parseCache == nil { parseCache = &ParseCache{} } - extendedConfigCache := &extendedConfigCache{} + extendedConfigCache := &ExtendedConfigCache{} session := &Session{ options: init.Options, @@ -148,7 +148,7 @@ func NewSession(init *SessionInit) *Session { snapshotID: atomic.Uint64{}, snapshot: NewSnapshot( uint64(0), - &snapshotFS{ + &SnapshotFS{ toPath: toPath, fs: init.FS, }, @@ -408,7 +408,7 @@ func (s *Session) GetLanguageService(ctx context.Context, uri lsproto.DocumentUr return ls.NewLanguageService(project.GetProgram(), snapshot), nil } -func (s *Session) UpdateSnapshot(ctx context.Context, overlays map[tspath.Path]*overlay, change SnapshotChange) *Snapshot { +func (s *Session) UpdateSnapshot(ctx context.Context, overlays map[tspath.Path]*Overlay, change SnapshotChange) *Snapshot { s.snapshotMu.Lock() oldSnapshot := s.snapshot newSnapshot := oldSnapshot.Clone(ctx, change, overlays, s) @@ -586,7 +586,7 @@ func (s *Session) Close() { s.backgroundQueue.Close() } -func (s *Session) flushChanges(ctx context.Context) (FileChangeSummary, map[tspath.Path]*overlay, map[tspath.Path]*ATAStateChange, *Config) { +func (s *Session) flushChanges(ctx context.Context) (FileChangeSummary, map[tspath.Path]*Overlay, map[tspath.Path]*ATAStateChange, *Config) { s.pendingFileChangesMu.Lock() defer s.pendingFileChangesMu.Unlock() s.pendingATAChangesMu.Lock() @@ -607,7 +607,7 @@ func (s *Session) flushChanges(ctx context.Context) (FileChangeSummary, map[tspa } // flushChangesLocked should only be called with s.pendingFileChangesMu held. -func (s *Session) flushChangesLocked(ctx context.Context) (FileChangeSummary, map[tspath.Path]*overlay) { +func (s *Session) flushChangesLocked(ctx context.Context) (FileChangeSummary, map[tspath.Path]*Overlay) { if len(s.pendingFileChanges) == 0 { return FileChangeSummary{}, s.fs.Overlays() } diff --git a/internal/project/snapshot.go b/internal/project/snapshot.go index 9c90c21455..ffb0181a42 100644 --- a/internal/project/snapshot.go +++ b/internal/project/snapshot.go @@ -30,7 +30,7 @@ type Snapshot struct { converters *ls.Converters // Immutable state, cloned between snapshots - fs *snapshotFS + fs *SnapshotFS ProjectCollection *ProjectCollection ConfigFileRegistry *ConfigFileRegistry compilerOptionsForInferredProjects *core.CompilerOptions @@ -43,10 +43,10 @@ type Snapshot struct { // NewSnapshot func NewSnapshot( id uint64, - fs *snapshotFS, + fs *SnapshotFS, sessionOptions *SessionOptions, parseCache *ParseCache, - extendedConfigCache *extendedConfigCache, + extendedConfigCache *ExtendedConfigCache, configFileRegistry *ConfigFileRegistry, compilerOptionsForInferredProjects *core.CompilerOptions, config Config, @@ -163,7 +163,7 @@ type ATAStateChange struct { Logs *logging.LogTree } -func (s *Snapshot) Clone(ctx context.Context, change SnapshotChange, overlays map[tspath.Path]*overlay, session *Session) *Snapshot { +func (s *Snapshot) Clone(ctx context.Context, change SnapshotChange, overlays map[tspath.Path]*Overlay, session *Session) *Snapshot { var logger *logging.LogTree // Print in-progress logs immediately if cloning fails diff --git a/internal/project/snapshotfs.go b/internal/project/snapshotfs.go index 1537b8d0aa..50023347e0 100644 --- a/internal/project/snapshotfs.go +++ b/internal/project/snapshotfs.go @@ -20,24 +20,24 @@ type FileSource interface { var ( _ FileSource = (*snapshotFSBuilder)(nil) - _ FileSource = (*snapshotFS)(nil) + _ FileSource = (*SnapshotFS)(nil) ) -type snapshotFS struct { +type SnapshotFS struct { toPath func(fileName string) tspath.Path fs vfs.FS - overlays map[tspath.Path]*overlay + overlays map[tspath.Path]*Overlay diskFiles map[tspath.Path]*diskFile readFiles collections.SyncMap[tspath.Path, memoizedDiskFile] } type memoizedDiskFile func() FileHandle -func (s *snapshotFS) FS() vfs.FS { +func (s *SnapshotFS) FS() vfs.FS { return s.fs } -func (s *snapshotFS) GetFile(fileName string) FileHandle { +func (s *SnapshotFS) GetFile(fileName string) FileHandle { if file, ok := s.overlays[s.toPath(fileName)]; ok { return file } @@ -56,14 +56,14 @@ func (s *snapshotFS) GetFile(fileName string) FileHandle { type snapshotFSBuilder struct { fs vfs.FS - overlays map[tspath.Path]*overlay + overlays map[tspath.Path]*Overlay diskFiles *dirty.SyncMap[tspath.Path, *diskFile] toPath func(string) tspath.Path } func newSnapshotFSBuilder( fs vfs.FS, - overlays map[tspath.Path]*overlay, + overlays map[tspath.Path]*Overlay, diskFiles map[tspath.Path]*diskFile, positionEncoding lsproto.PositionEncodingKind, toPath func(fileName string) tspath.Path, @@ -82,9 +82,9 @@ func (s *snapshotFSBuilder) FS() vfs.FS { return s.fs } -func (s *snapshotFSBuilder) Finalize() (*snapshotFS, bool) { +func (s *snapshotFSBuilder) Finalize() (*SnapshotFS, bool) { diskFiles, changed := s.diskFiles.Finalize() - return &snapshotFS{ + return &SnapshotFS{ fs: s.fs, overlays: s.overlays, diskFiles: diskFiles, diff --git a/internal/project/watch.go b/internal/project/watch.go index 2354040e3e..cdab89ad13 100644 --- a/internal/project/watch.go +++ b/internal/project/watch.go @@ -30,7 +30,7 @@ type fileSystemWatcherValue struct { id WatcherID } -type patternsAndIgnored struct { +type PatternsAndIgnored struct { patterns []string ignored map[string]struct{} } @@ -53,7 +53,7 @@ var watcherID atomic.Uint64 type WatchedFiles[T any] struct { name string watchKind lsproto.WatchKind - computeGlobPatterns func(input T) patternsAndIgnored + computeGlobPatterns func(input T) PatternsAndIgnored mu sync.RWMutex input T @@ -63,7 +63,7 @@ type WatchedFiles[T any] struct { id uint64 } -func NewWatchedFiles[T any](name string, watchKind lsproto.WatchKind, computeGlobPatterns func(input T) patternsAndIgnored) *WatchedFiles[T] { +func NewWatchedFiles[T any](name string, watchKind lsproto.WatchKind, computeGlobPatterns func(input T) PatternsAndIgnored) *WatchedFiles[T] { return &WatchedFiles[T]{ id: watcherID.Add(1), name: name, @@ -129,13 +129,13 @@ func (w *WatchedFiles[T]) Clone(input T) *WatchedFiles[T] { } } -func createResolutionLookupGlobMapper(workspaceDirectory string, libDirectory string, currentDirectory string, useCaseSensitiveFileNames bool) func(data map[tspath.Path]string) patternsAndIgnored { +func createResolutionLookupGlobMapper(workspaceDirectory string, libDirectory string, currentDirectory string, useCaseSensitiveFileNames bool) func(data map[tspath.Path]string) PatternsAndIgnored { comparePathsOptions := tspath.ComparePathsOptions{ CurrentDirectory: currentDirectory, UseCaseSensitiveFileNames: useCaseSensitiveFileNames, } - return func(data map[tspath.Path]string) patternsAndIgnored { + return func(data map[tspath.Path]string) PatternsAndIgnored { var ignored map[string]struct{} var seenDirs collections.Set[string] var includeWorkspace, includeRoot, includeLib bool @@ -196,7 +196,7 @@ func createResolutionLookupGlobMapper(workspaceDirectory string, libDirectory st } } - return patternsAndIgnored{ + return PatternsAndIgnored{ patterns: globs, ignored: ignored, } @@ -209,7 +209,7 @@ func getTypingsLocationsGlobs( workspaceDirectory string, currentDirectory string, useCaseSensitiveFileNames bool, -) patternsAndIgnored { +) PatternsAndIgnored { var includeTypingsLocation, includeWorkspace bool externalDirectories := make(map[tspath.Path]string) globs := make(map[tspath.Path]string) @@ -243,7 +243,7 @@ func getTypingsLocationsGlobs( for _, dir := range externalDirectoryParents { globs[tspath.ToPath(dir, currentDirectory, useCaseSensitiveFileNames)] = getRecursiveGlobPattern(dir) } - return patternsAndIgnored{ + return PatternsAndIgnored{ patterns: slices.Collect(maps.Values(globs)), ignored: ignored, } @@ -315,7 +315,7 @@ func extractLookups[T resolutionWithLookupLocations]( } } -func getNonRootFileGlobs(workspaceDir string, libDirectory string, sourceFiles []*ast.SourceFile, rootFiles map[tspath.Path]string, comparePathsOptions tspath.ComparePathsOptions) patternsAndIgnored { +func getNonRootFileGlobs(workspaceDir string, libDirectory string, sourceFiles []*ast.SourceFile, rootFiles map[tspath.Path]string, comparePathsOptions tspath.ComparePathsOptions) PatternsAndIgnored { var globs []string var includeWorkspace, includeLib bool var ignored map[string]struct{} @@ -350,7 +350,7 @@ func getNonRootFileGlobs(workspaceDir string, libDirectory string, sourceFiles [ })...) ignored = ignoredDirs } - return patternsAndIgnored{ + return PatternsAndIgnored{ patterns: globs, ignored: ignored, } diff --git a/internal/repo/paths.go b/internal/repo/paths.go index 237a8d0467..2d329b1b61 100644 --- a/internal/repo/paths.go +++ b/internal/repo/paths.go @@ -50,12 +50,12 @@ func TypeScriptSubmoduleExists() bool { return typeScriptSubmoduleExists() } -type skippable interface { +type SkippableTest interface { Helper() Skipf(format string, args ...any) } -func SkipIfNoTypeScriptSubmodule(t skippable) { +func SkipIfNoTypeScriptSubmodule(t SkippableTest) { t.Helper() if !typeScriptSubmoduleExists() { t.Skipf("TypeScript submodule does not exist") diff --git a/internal/vfs/utilities.go b/internal/vfs/utilities.go index d86a7f0d10..3dd8244377 100644 --- a/internal/vfs/utilities.go +++ b/internal/vfs/utilities.go @@ -24,15 +24,15 @@ type FileMatcherPatterns struct { basePaths []string } -type usage string +type Usage string const ( - usageFiles usage = "files" - usageDirectories usage = "directories" - usageExclude usage = "exclude" + usageFiles Usage = "files" + usageDirectories Usage = "directories" + usageExclude Usage = "exclude" ) -func GetRegularExpressionsForWildcards(specs []string, basePath string, usage usage) []string { +func GetRegularExpressionsForWildcards(specs []string, basePath string, usage Usage) []string { if len(specs) == 0 { return nil } @@ -41,7 +41,7 @@ func GetRegularExpressionsForWildcards(specs []string, basePath string, usage us }) } -func GetRegularExpressionForWildcard(specs []string, basePath string, usage usage) string { +func GetRegularExpressionForWildcard(specs []string, basePath string, usage Usage) string { patterns := GetRegularExpressionsForWildcards(specs, basePath, usage) if len(patterns) == 0 { return "" @@ -138,7 +138,7 @@ var excludeMatcher = WildcardMatcher{ }, } -var wildcardMatchers = map[usage]WildcardMatcher{ +var wildcardMatchers = map[Usage]WildcardMatcher{ usageFiles: filesMatcher, usageDirectories: directoriesMatcher, usageExclude: excludeMatcher, @@ -147,7 +147,7 @@ var wildcardMatchers = map[usage]WildcardMatcher{ func GetPatternFromSpec( spec string, basePath string, - usage usage, + usage Usage, ) string { pattern := getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]) if pattern == "" { @@ -160,7 +160,7 @@ func GetPatternFromSpec( func getSubPatternFromSpec( spec string, basePath string, - usage usage, + usage Usage, matcher WildcardMatcher, ) string { matcher = wildcardMatchers[usage]