Documentation
¶
Index ¶
- Variables
- func AccessExpressionObject(node *ast.Node) *ast.Node
- func AccessExpressionStaticName(node *ast.Node) (string, bool)
- func BlockEndsWithTerminal(block *ast.Node) bool
- func CanBlockThrow(block *ast.Node) bool
- func CollectAllCallSignatures(typeChecker *checker.Checker, t *checker.Type) []*checker.Signature
- func CollectBindingNames(nameNode *ast.Node, callback func(ident *ast.Node, name string))
- func CollectProgramFiles(programs []*compiler.Program, fs vfs.FS) map[string]struct{}
- func ComparePaths(a string, b string, program *compiler.Program) int
- func CreateCompilerHost(cwd string, fs vfs.FS) compiler.CompilerHost
- func CreateProgram(singleThreaded bool, fs vfs.FS, cwd string, tsconfigPath string, ...) (*compiler.Program, error)
- func CreateProgramFromOptions(singleThreaded bool, compilerOptions *core.CompilerOptions, ...) (*compiler.Program, error)
- func CreateProgramFromOptionsLenient(singleThreaded bool, compilerOptions *core.CompilerOptions, ...) (*compiler.Program, error)
- func DefaultIgnoreDirGlobs() []string
- func Every[T any](slice []T, f func(T) bool) bool
- func ExtractRegexPatternAndFlags(text string) (pattern string, flags string)
- func Filter[T any](slice []T, f func(T) bool) []T
- func FilterIndex[T any](slice []T, f func(T, int, []T) bool) []T
- func FindEnclosingScope(node *ast.Node) *ast.Node
- func Flatten[T any](array [][]T) []T
- func ForEachComment(node *ast.Node, callback func(comment *ast.CommentRange), ...)
- func ForEachToken(node *ast.Node, callback func(token *ast.Node), sourceFile *ast.SourceFile)
- func GetCallSignatures(typeChecker *checker.Checker, t *checker.Type) []*checker.Signature
- func GetChildren(node *ast.Node, sourceFile *ast.SourceFile) []*ast.Node
- func GetCommentsInRange(sourceFile *ast.SourceFile, inRange core.TextRange) iter.Seq[ast.CommentRange]
- func GetConstrainedTypeAtLocation(typeChecker *checker.Checker, node *ast.Node) *checker.Type
- func GetConstraintInfo(typeChecker *checker.Checker, t *checker.Type) (constraintType *checker.Type, isTypeParameter bool)
- func GetConstructSignatures(typeChecker *checker.Checker, t *checker.Type) []*checker.Signature
- func GetContextualType(typeChecker *checker.Checker, node *ast.Node) *checker.Type
- func GetDeclaration(typeChecker *checker.Checker, node *ast.Node) *ast.Declaration
- func GetDeclarationIdentifier(decl *ast.Node) *ast.Node
- func GetEnumLiterals(t *checker.Type) []*checker.Type
- func GetEnumTypes(typeChecker *checker.Checker, t *checker.Type) []*checker.Type
- func GetForStatementHeadLoc(sourceFile *ast.SourceFile, node *ast.Node) core.TextRange
- func GetFunctionHeadLoc(sourceFile *ast.SourceFile, node *ast.Node) core.TextRange
- func GetHeritageClauses(node *ast.Node) *ast.NodeList
- func GetImportBindingNodes(node *ast.Node) []*ast.Node
- func GetNumberIndexType(typeChecker *checker.Checker, t *checker.Type) *checker.Type
- func GetOptionsMap(opts any) map[string]interface{}
- func GetOptionsString(opts any) string
- func GetParentFunctionNode(node *ast.Node) *ast.Node
- func GetPropertyInfo(sourceFile *ast.SourceFile, node *ast.Node) (*ast.Node, string)
- func GetStaticExpressionValue(node *ast.Node) (string, bool)
- func GetStaticPropertyName(nameNode *ast.Node) (string, bool)
- func GetStaticStringValue(node *ast.Node) string
- func GetThisExpression(node *ast.Node) *ast.Node
- func GetTypeName(typeChecker *checker.Checker, t *checker.Type) string
- func GetWellKnownSymbolPropertyOfType(t *checker.Type, name string, typeChecker *checker.Checker) *ast.Symbol
- func HasCommentsInRange(sourceFile *ast.SourceFile, inRange core.TextRange) bool
- func HasHoistedVarDeclaration(node *ast.Node, name string) bool
- func HasLocalDeclarationInStatements(statements []*ast.Node, name string) bool
- func HasNameInBindingPattern(pattern *ast.Node, name string) bool
- func HasShadowingDeclaration(node *ast.Node, name string) bool
- func HasShadowingParameter(node *ast.Node, name string) bool
- func HasUseStrictDirective(block *ast.Node) bool
- func HasVarDeclListWithName(node *ast.Node, name string) bool
- func IncludesModifier(node interface{ ... }, modifier ast.Kind) bool
- func IntersectionTypeParts(t *checker.Type) []*checker.Type
- func IsAnyBuiltinSymbolLike(program *compiler.Program, typeChecker *checker.Checker, t *checker.Type) bool
- func IsArrayMethodCallWithPredicate(typeChecker *checker.Checker, node *ast.CallExpression) bool
- func IsBindingPatternInAssignment(node *ast.Node) bool
- func IsBooleanLiteralType(t *checker.Type) bool
- func IsBuiltinSymbolLike(program *compiler.Program, typeChecker *checker.Checker, t *checker.Type, ...) bool
- func IsBuiltinSymbolLikeRecurser(program *compiler.Program, typeChecker *checker.Checker, t *checker.Type, ...) bool
- func IsBuiltinTypeAliasLike(program *compiler.Program, typeChecker *checker.Checker, t *checker.Type, ...) bool
- func IsCallback(typeChecker *checker.Checker, param *ast.Symbol, node *ast.Node) bool
- func IsCallee(node *ast.Node) bool
- func IsDeclarationIdentifier(node *ast.Node) bool
- func IsDefaultThisBinding(node *ast.Node) bool
- func IsErrorLike(program *compiler.Program, typeChecker *checker.Checker, t *checker.Type) bool
- func IsFalseLiteralType(t *checker.Type) bool
- func IsFunctionEndReachable(node *ast.Node) bool
- func IsHigherPrecedenceThanAwait(node *ast.Node) bool
- func IsInDestructuringAssignment(node *ast.Node) bool
- func IsInObjectLiteralMethod(functionNode *ast.Node) bool
- func IsInStrictMode(node *ast.Node, sourceFile *ast.SourceFile) bool
- func IsIntersectionType(t *checker.Type) bool
- func IsIntrinsicErrorType(t *checker.Type) bool
- func IsIntrinsicType(t *checker.Type) bool
- func IsIntrinsicVoidType(t *checker.Type) bool
- func IsNonReferenceIdentifier(node *ast.Node) bool
- func IsNullLiteral(node *ast.Node) bool
- func IsNullOrUndefined(node *ast.Node) bool
- func IsNullableType(t *checker.Type) bool
- func IsObjectType(t *checker.Type) bool
- func IsParenlessArrowFunction(node *ast.Node) bool
- func IsPossiblyFalsy(t *checker.Type) bool
- func IsPossiblyTruthy(t *checker.Type) bool
- func IsPromiseConstructorLike(program *compiler.Program, typeChecker *checker.Checker, t *checker.Type) bool
- func IsPromiseLike(program *compiler.Program, typeChecker *checker.Checker, t *checker.Type) bool
- func IsReadonlyErrorLike(program *compiler.Program, typeChecker *checker.Checker, t *checker.Type) bool
- func IsReadonlyTypeLike(program *compiler.Program, typeChecker *checker.Checker, t *checker.Type, ...) bool
- func IsRestParameterDeclaration(decl *ast.Declaration) bool
- func IsSameReference(left, right *ast.Node) bool
- func IsShadowed(node *ast.Node, name string) bool
- func IsSourceFileDefaultLibrary(program *compiler.Program, file *ast.SourceFile) bool
- func IsStrWhiteSpace(r rune) bool
- func IsStrictCompilerOptionEnabled(options *core.CompilerOptions, option core.Tristate) bool
- func IsStrongPrecedenceNode(innerNode *ast.Node) bool
- func IsSymbolDeclaredInFile(symbol *ast.Symbol, sf *ast.SourceFile) bool
- func IsSymbolFlagSet(symbol *ast.Symbol, flag ast.SymbolFlags) bool
- func IsSymbolFromDefaultLibrary(program *compiler.Program, symbol *ast.Symbol) bool
- func IsThenableType(typeChecker *checker.Checker, node *ast.Node, t *checker.Type) bool
- func IsTrueLiteralType(t *checker.Type) bool
- func IsTypeAnyArrayType(t *checker.Type, typeChecker *checker.Checker) bool
- func IsTypeAnyType(t *checker.Type) bool
- func IsTypeFlagSet(t *checker.Type, flags checker.TypeFlags) bool
- func IsTypeFlagSetWithUnion(t *checker.Type, flags checker.TypeFlags) bool
- func IsTypeParameter(t *checker.Type) bool
- func IsTypeUnknownArrayType(t *checker.Type, typeChecker *checker.Checker) bool
- func IsTypeUnknownType(t *checker.Type) bool
- func IsUnionType(t *checker.Type) bool
- func IsUnsafeAssignment(t *checker.Type, receiverT *checker.Type, typeChecker *checker.Checker, ...) (receiver *checker.Type, sender *checker.Type, unsafe bool)
- func IsVarKeyword(node *ast.Node) bool
- func IsWriteReference(node *ast.Node) bool
- func Map[T, U any](slice []T, f func(T) U) []U
- func Must[T any](v T, err error) T
- func NaturalCompare(a, b string) int
- func NewOverlayVFS(baseFS vfs.FS, virtualFiles map[string]string) vfs.FS
- func NewOverlayVFSForFile(filePath string, source string) vfs.FS
- func NormalizeBigIntLiteral(text string) string
- func NormalizeNumericLiteral(text string) string
- func ParseJSONC(data []byte, v interface{}) error
- func Ref[T any](a T) *T
- func Some[T any](slice []T, f func(T) bool) bool
- func StripJSONComments(jsoncString string) string
- func ToStringSlice(val interface{}) []string
- func TrimNodeTextRange(sourceFile *ast.SourceFile, node *ast.Node) core.TextRange
- func TrimmedNodeText(sourceFile *ast.SourceFile, node *ast.Node) string
- func TypeMatchesSomeSpecifier(t *checker.Type, specifiers []TypeOrValueSpecifier, inlineSpecifiers []string, ...) bool
- func TypeMatchesSomeSpecifierWithCalleeNames(t *checker.Type, specifiers []TypeOrValueSpecifier, inlineSpecifiers []string, ...) bool
- func TypeRecurser(t *checker.Type, predicate func(t *checker.Type) bool) bool
- func UnionTypeParts(t *checker.Type) []*checker.Type
- func VisitDestructuringIdentifiers(node *ast.Node, fn func(*ast.Node))
- type ConstraintTypeInfo
- type DiscriminatedAnyType
- type FunctionReturnAnalysis
- type MemberNameType
- type NameList
- type OverlayVFS
- func (vfs *OverlayVFS) Chtimes(path string, atime time.Time, mtime time.Time) error
- func (vfs *OverlayVFS) DirectoryExists(path string) bool
- func (vfs *OverlayVFS) FileExists(path string) bool
- func (vfs *OverlayVFS) GetAccessibleEntries(path string) (result vfs.Entries)
- func (vfs *OverlayVFS) ReadFile(path string) (contents string, ok bool)
- func (vfs *OverlayVFS) Realpath(path string) string
- func (vfs *OverlayVFS) Remove(path string) error
- func (vfs *OverlayVFS) Stat(path string) vfs.FileInfo
- func (vfs *OverlayVFS) UseCaseSensitiveFileNames() bool
- func (vfs *OverlayVFS) WalkDir(root string, walkFn vfs.WalkDirFunc) error
- func (vfs *OverlayVFS) WriteFile(path string, data string) error
- type Set
- type SyntacticError
- type TypeAwaitable
- type TypeOrValueSpecifier
- type TypeOrValueSpecifierFrom
Constants ¶
This section is empty.
Variables ¶
var DefaultExcludeDirNames = []string{"node_modules", ".git"}
DefaultExcludeDirNames contains directory names that are always excluded from file scanning. This is the single source of truth for default directory exclusions, used by DiscoverGapFiles and the no-tsconfig fallback. Aligned with JS-side SCAN_EXCLUDE_DIRS: new Set(['node_modules', '.git']).
var ExcludePaths = []string{"/node_modules/", "bundled:"}
ExcludePaths contains path substrings that should be excluded from linting. Used by RunLinterInProgram to skip files during program source file iteration.
Functions ¶
func AccessExpressionObject ¶ added in v0.11.0
AccessExpressionObject returns the object expression of an access expression.
func AccessExpressionStaticName ¶ added in v0.11.0
AccessExpressionStaticName returns the static property name of an access expression (PropertyAccessExpression or ElementAccessExpression), or ("", false) if not static.
func BlockEndsWithTerminal ¶ added in v0.11.0
BlockEndsWithTerminal checks if a block's last statement is a control flow terminal (break/return/throw/continue), possibly nested in inner blocks.
func CanBlockThrow ¶ added in v0.11.0
CanBlockThrow checks if a block can throw before reaching a non-throwing terminal. Used to determine if a catch clause is reachable.
A block "can throw" if it contains any statement that may raise an exception before control reaches a guaranteed non-throwing terminal (break, continue, or return without expression). Specifically:
- break / continue: non-throwing terminals → returns false
- return (no expression): non-throwing → returns false
- return (with expression): expression evaluation may throw → returns true
- throw: always throws → returns true
- empty statement: no effect → continues checking
- nested block: recurses
- try with finally that terminates: finally overrides → returns false
- any other statement (expression, if, for, etc.): may throw → returns true
func CollectAllCallSignatures ¶
ex. getCallSignaturesOfType
func CollectBindingNames ¶
CollectBindingNames recursively extracts all identifier names from a binding pattern (ObjectBindingPattern, ArrayBindingPattern) or plain Identifier. For each identifier found, it calls the callback with the identifier node and its name.
func CollectProgramFiles ¶ added in v0.11.0
CollectProgramFiles collects all source file paths from the given programs into a set for fast lookup. Also stores symlink-resolved paths to handle platform differences (e.g. macOS /tmp → /private/tmp).
func CreateCompilerHost ¶
func CreateCompilerHost(cwd string, fs vfs.FS) compiler.CompilerHost
func CreateProgram ¶
func CreateProgramFromOptions ¶
func CreateProgramFromOptions(singleThreaded bool, compilerOptions *core.CompilerOptions, rootFileNames []string, host compiler.CompilerHost) (*compiler.Program, error)
CreateProgramFromOptions creates a program from in-memory compiler options and root file names, without requiring a tsconfig file on disk.
func CreateProgramFromOptionsLenient ¶ added in v0.11.0
func CreateProgramFromOptionsLenient(singleThreaded bool, compilerOptions *core.CompilerOptions, rootFileNames []string, host compiler.CompilerHost) (*compiler.Program, error)
CreateProgramFromOptionsLenient creates a program like CreateProgramFromOptions but tolerates syntactic errors. This is used for fallback programs where the user's source code may contain syntax errors (that's why they're running a linter).
func DefaultIgnoreDirGlobs ¶ added in v0.11.0
func DefaultIgnoreDirGlobs() []string
DefaultIgnoreDirGlobs returns glob patterns derived from DefaultExcludeDirNames, suitable for use with ignore pattern matching (e.g., DiscoverGapFiles).
func ExtractRegexPatternAndFlags ¶ added in v0.11.0
GetOptionsMap extracts a map[string]interface{} from rule options. It handles both array format [{ option: value }] and direct object format { option: value }. ExtractRegexPatternAndFlags splits a RegularExpressionLiteral's text (e.g. "/pattern/gi") into the pattern and flags portions. Returns ("", "") for malformed input.
func FilterIndex ¶
Source: typescript-go/internal/core/core.go
func FindEnclosingScope ¶ added in v0.11.0
FindEnclosingScope finds the nearest function-like, class static block, module block, or source file scope for a node. Uses the tsgo public function IsFunctionLikeOrClassStaticBlockDeclaration. This is commonly needed by rules that walk write references or check variable scoping (e.g. prefer-const, no-var, no-class-assign).
func ForEachComment ¶
func ForEachComment(node *ast.Node, callback func(comment *ast.CommentRange), sourceFile *ast.SourceFile)
Iterates over all comments owned by `node` or its children.
@category Nodes - Other Utilities
@example
declare const node: ts.Node;
forEachComment(node, (fullText, comment) => {
console.log(`Found comment at position ${comment.pos}: '${fullText}'.`);
});
func ForEachToken ¶
Iterates over all tokens of `node`
@category Nodes - Other Utilities
@example
declare const node: ts.Node;
forEachToken(node, (token) => {
console.log("Found token:", token.getText());
});
@param node The node whose tokens should be visited @param callback Is called for every token contained in `node`
func GetCallSignatures ¶
func GetChildren ¶
getChildrenFromNonJSDocNode from github.com/microsoft/typescript-go/internal/ls/utilities.go
func GetCommentsInRange ¶
func GetCommentsInRange(sourceFile *ast.SourceFile, inRange core.TextRange) iter.Seq[ast.CommentRange]
func GetConstraintInfo ¶
func GetConstraintInfo( typeChecker *checker.Checker, t *checker.Type, ) (constraintType *checker.Type, isTypeParameter bool)
*
- Returns whether the type is a generic and what its constraint is. *
- If the type is not a generic, `isTypeParameter` will be `false`, and
- `constraintType` will be the same as the input type. *
- If the type is a generic, and it is constrained, `isTypeParameter` will be
- `true`, and `constraintType` will be the constraint type. *
- If the type is a generic, but it is not constrained, `constraintType` will be
- `undefined` (rather than an `unknown` type), due to https://github.com/microsoft/TypeScript/issues/60475 *
- Successor to {@link getConstrainedTypeAtLocation} due to https://github.com/typescript-eslint/typescript-eslint/issues/10438 *
- This is considered internal since it is unstable for now and may have breaking changes at any time.
- Use at your own risk. *
- @internal *
func GetConstructSignatures ¶
func GetContextualType ¶
*
- Returns the contextual type of a given node.
- Contextual type is the type of the target the node is going into.
- i.e. the type of a called function's parameter, or the defined type of a variable declaration
func GetDeclarationIdentifier ¶ added in v0.11.0
GetDeclarationIdentifier returns the name node of a declaration.
func GetEnumLiterals ¶
*
- Retrieve only the Enum literals from a type. for example:
- - 123 --> []
- - {} --> []
- - Fruit.Apple --> [Fruit.Apple]
- - Fruit.Apple | Vegetable.Lettuce --> [Fruit.Apple, Vegetable.Lettuce]
- - Fruit.Apple | Vegetable.Lettuce | 123 --> [Fruit.Apple, Vegetable.Lettuce]
- - T extends Fruit --> [Fruit]
func GetEnumTypes ¶
*
- A type can have 0 or more enum types. For example:
- - 123 --> []
- - {} --> []
- - Fruit.Apple --> [Fruit]
- - Fruit.Apple | Vegetable.Lettuce --> [Fruit, Vegetable]
- - Fruit.Apple | Vegetable.Lettuce | 123 --> [Fruit, Vegetable]
- - T extends Fruit --> [Fruit]
func GetForStatementHeadLoc ¶
*
- Gets the location of the head of the given for statement variant for reporting. *
- - `for (const foo in bar) expressionOrBlock`
- ^^^^^^^^^^^^^^^^^^^^^^ *
- - `for (const foo of bar) expressionOrBlock`
- ^^^^^^^^^^^^^^^^^^^^^^ *
- - `for await (const foo of bar) expressionOrBlock`
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *
- - `for (let i = 0; i < 10; i++) expressionOrBlock`
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
func GetFunctionHeadLoc ¶ added in v0.11.0
*
- Gets the location of a function node's "head" for reporting.
- Matches the behavior of typescript-eslint's getFunctionHeadLoc: *
- - `function foo() {}` → `function foo`
- - `(function() {})` → `function`
- - `() => {}` → `=>`
- - `class A { method() {} }` → `method`
- - `class A { get foo() {} }` → `get foo`
- - `class A { static async foo() {} }` → `static async foo`
- - `class A { foo = () => {} }` → `foo = `
- - `{ foo: function() {} }` → `foo: function`
- - `export default function() {}` → `function`
func GetImportBindingNodes ¶ added in v0.11.0
GetImportBindingNodes returns the local binding identifier nodes declared by an import statement. Returns nil for side-effect imports (e.g. `import 'foo'`). Handles ImportDeclaration (default, named, namespace) and ImportEqualsDeclaration.
func GetNumberIndexType ¶
func GetOptionsMap ¶
func GetOptionsString ¶ added in v0.11.0
GetOptionsString extracts a string option from the weakly-typed options parameter. It handles both direct string format ("value") and array format (["value"]).
func GetPropertyInfo ¶
GetPropertyInfo extracts the property node and formatted property name from a PropertyAccessExpression or ElementAccessExpression. Returns the property node and a formatted string like ".propertyName" or "[index]". Returns (nil, "") if the node is neither a property access nor an element access expression.
Note: When called from ast.KindPropertyAccessExpression or ast.KindElementAccessExpression listeners, the returned property is guaranteed to be non-nil because:
- PropertyAccessExpression.Name() always returns a valid Identifier node
- ElementAccessExpression.ArgumentExpression always exists (after SkipParentheses)
The nil return case only applies when called with nodes of other types.
func GetStaticExpressionValue ¶ added in v0.11.0
GetStaticExpressionValue returns the static string value of a literal expression, or ("", false) if the value cannot be statically determined.
Unlike GetStaticPropertyName, which is designed for property name nodes (Identifier, ComputedPropertyName, etc.) and treats Identifier as a static name, this function is for arbitrary value expressions — it only recognizes compile-time-constant literals and does NOT treat Identifier as static (since a[b] where b is a variable is dynamic).
Supported node kinds:
- StringLiteral: returns the string value
- NumericLiteral: returns the normalized numeric string (e.g. "0x1" → "1")
- NoSubstitutionTemplateLiteral: returns the template text
- RegularExpressionLiteral: returns the source text (e.g. /foo/g), matching JavaScript's implicit toString coercion when used as a property key
This is the expression-level complement to GetStaticPropertyName: use GetStaticPropertyName for property name nodes (object keys, class members), and GetStaticExpressionValue for value positions (element access arguments, etc.).
func GetStaticPropertyName ¶
GetStaticPropertyName extracts the static name from a property name node. It handles Identifier, StringLiteral, NumericLiteral, and ComputedPropertyName (with static string, numeric, BigInt, or template literal expressions). Returns the name and whether it's a static (non-computed or statically-computable) name.
func GetStaticStringValue ¶ added in v0.11.0
GetStaticStringValue returns the string value if the node is a string literal or a no-substitution template literal. Returns "" if the value cannot be statically determined.
func GetTypeName ¶
*
- Get the type name of a given type.
- @param typeChecker The context sensitive TypeScript TypeChecker.
- @param type The type to get the name of.
func HasCommentsInRange ¶
func HasCommentsInRange(sourceFile *ast.SourceFile, inRange core.TextRange) bool
func HasHoistedVarDeclaration ¶ added in v0.11.0
HasHoistedVarDeclaration recursively scans a subtree for `var` declarations with the given name. It stops at nested function boundaries and module declarations since `var` does not hoist past them.
func HasLocalDeclarationInStatements ¶ added in v0.11.0
HasLocalDeclarationInStatements checks if a list of top-level statements (typically from a SourceFile) contains a variable, function, class, enum, module, or import declaration with the given name.
func HasNameInBindingPattern ¶ added in v0.11.0
HasNameInBindingPattern checks if a binding pattern (including nested destructuring) contains a binding with the given name.
func HasShadowingDeclaration ¶ added in v0.11.0
HasShadowingDeclaration checks if a block contains a variable, function, or class declaration whose name matches the given name.
func HasShadowingParameter ¶ added in v0.11.0
HasShadowingParameter checks if a function-like node has a parameter whose binding name matches the given name (supports destructuring patterns).
func HasUseStrictDirective ¶ added in v0.11.0
HasUseStrictDirective checks if a block or source file starts with a "use strict" directive.
func HasVarDeclListWithName ¶ added in v0.11.0
HasVarDeclListWithName checks if a VariableDeclarationList contains a declaration with the given name (supports destructuring).
func IncludesModifier ¶
func IncludesModifier(node interface{ Modifiers() *ast.ModifierList }, modifier ast.Kind) bool
func IsAnyBuiltinSymbolLike ¶
func IsArrayMethodCallWithPredicate ¶
func IsArrayMethodCallWithPredicate( typeChecker *checker.Checker, node *ast.CallExpression, ) bool
func IsBindingPatternInAssignment ¶ added in v0.11.0
IsBindingPatternInAssignment checks if a binding pattern is the left side of an assignment.
func IsBooleanLiteralType ¶
func IsBuiltinSymbolLike ¶
func IsBuiltinTypeAliasLike ¶
func IsCallback ¶
func IsCallee ¶ added in v0.11.0
IsCallee checks if a node is the callee of a CallExpression or NewExpression, skipping parentheses and TS type assertions between the node and the call.
func IsDeclarationIdentifier ¶ added in v0.11.0
IsDeclarationIdentifier checks if the node is the name (identifier) of a declaration. Unlike ast.IsDeclarationName(), this returns false for ShorthandPropertyAssignment names since they are both declaration names AND value references.
func IsDefaultThisBinding ¶ added in v0.11.0
IsDefaultThisBinding checks whether a function's 'this' binding defaults to the global object. This mirrors ESLint's astUtils.isDefaultThisBinding. Returns true when 'this' defaults to global; false when explicitly bound.
func IsFalseLiteralType ¶
IsFalseLiteralType checks if the type is the boolean literal `false`.
func IsFunctionEndReachable ¶
IsFunctionEndReachable checks if a function's end is reachable (can fall through without a return or throw statement). Uses the binder's NodeFlagsHasImplicitReturn flag.
func IsInDestructuringAssignment ¶ added in v0.11.0
IsInDestructuringAssignment checks if a node is part of a destructuring assignment pattern. Walks up from the node through nested array/object literals to find a top-level destructuring assignment (e.g. [{a}] = [...] or {x: [a]} = {...}).
func IsInObjectLiteralMethod ¶
IsInObjectLiteralMethod checks if a function node is defined as a method in an object literal. This includes both shorthand method syntax ({ methodA() {} }) and property assignment syntax ({ methodA: function() {} }). Returns true if the function is an object literal method.
func IsInStrictMode ¶ added in v0.11.0
func IsInStrictMode(node *ast.Node, sourceFile *ast.SourceFile) bool
IsInStrictMode checks whether a node is in strict mode code. Strict mode is active when:
- The file is an ES module (has import/export)
- The file or an enclosing function has a "use strict" directive
- The node is inside a class body (class bodies are implicitly strict in ES2015+)
func IsIntersectionType ¶
func IsIntrinsicErrorType ¶
func IsIntrinsicType ¶
func IsIntrinsicVoidType ¶
func IsNonReferenceIdentifier ¶ added in v0.11.0
IsNonReferenceIdentifier checks if an identifier is NOT a value reference (i.e., it's a declaration name, property key, label, or module specifier name rather than a reference to a variable).
func IsNullLiteral ¶ added in v0.11.0
IsNullLiteral checks if a node is the null keyword, unwrapping parentheses.
func IsNullOrUndefined ¶ added in v0.11.0
IsNullOrUndefined checks if a node is a null literal, undefined identifier, or void expression, unwrapping parentheses.
func IsNullableType ¶ added in v0.11.0
IsNullableType checks if the type includes null, undefined, void, any or unknown. This matches typescript-eslint's isNullableType utility.
func IsObjectType ¶
func IsPossiblyFalsy ¶ added in v0.11.0
IsPossiblyFalsy checks if any union constituent of the type could be falsy.
func IsPossiblyTruthy ¶ added in v0.11.0
IsPossiblyTruthy checks if any union constituent of the type could be truthy.
func IsPromiseConstructorLike ¶
func IsPromiseConstructorLike( program *compiler.Program, typeChecker *checker.Checker, t *checker.Type, ) bool
*
- @example
- ```ts
- const value = Promise
- value.reject
- // ^ PromiseConstructorLike
- ```
func IsPromiseLike ¶
*
- @example
- ```ts
- class DerivedClass extends Promise<number> {}
- DerivedClass.reject
- // ^ PromiseLike
- ```
func IsReadonlyErrorLike ¶
func IsReadonlyErrorLike( program *compiler.Program, typeChecker *checker.Checker, t *checker.Type, ) bool
*
- @example
- ```ts
- type T = Readonly<Error>
- // ^ ReadonlyErrorLike
- ```
func IsReadonlyTypeLike ¶
func IsReadonlyTypeLike( program *compiler.Program, typeChecker *checker.Checker, t *checker.Type, predicate func(subType *checker.Type) bool, ) bool
*
- @example
- ```ts
- type T = Readonly<{ foo: 'bar' }>
- // ^ ReadonlyTypeLike
- ```
func IsRestParameterDeclaration ¶
func IsRestParameterDeclaration(decl *ast.Declaration) bool
func IsSameReference ¶ added in v0.11.0
IsSameReference reports whether two AST nodes refer to the same runtime value. It recursively compares member expression chains (PropertyAccessExpression, ElementAccessExpression), walking through the object/property structure.
Behavior details:
- Parenthesized expressions and type assertions (as, <T>) are transparently unwrapped on both sides via ast.SkipOuterExpressions.
- Optional chaining is ignored: a.b and a?.b are considered the same reference, matching ESLint's isSameReference semantics.
- Cross-syntax comparison is supported via static property names: a.b and a['b'] are the same reference; a[0] and a['0'] likewise.
- For non-static element access (a[x]), falls back to comparing the argument nodes structurally (same Kind + same Identifier/ThisKeyword).
- Function calls break the chain: a.b() and a.b() are NOT the same reference, because each call may return a different value.
This implements the same logic as ESLint's astUtils.isSameReference combined with astUtils.getStaticPropertyName, adapted for the TypeScript AST.
func IsShadowed ¶ added in v0.11.0
IsShadowed checks whether the given identifier name is shadowed by a local declaration at the usage site. It walks from node up to the SourceFile, checking every scope boundary for variable/function/class/enum/import declarations, function parameters, catch variables, and hoisted var declarations.
func IsSourceFileDefaultLibrary ¶
func IsSourceFileDefaultLibrary(program *compiler.Program, file *ast.SourceFile) bool
func IsStrWhiteSpace ¶
func IsStrictCompilerOptionEnabled ¶
func IsStrictCompilerOptionEnabled( options *core.CompilerOptions, option core.Tristate, ) bool
Checks if a given compiler option is enabled, accounting for whether all flags (except `strictPropertyInitialization`) have been enabled by `strict: true`.
@category Compiler Options
@example
const optionsLenient = {
noImplicitAny: true,
};
isStrictCompilerOptionEnabled(optionsLenient, "noImplicitAny"); // true isStrictCompilerOptionEnabled(optionsLenient, "noImplicitThis"); // false
@example
const optionsStrict = {
noImplicitThis: false,
strict: true,
};
isStrictCompilerOptionEnabled(optionsStrict, "noImplicitAny"); // true isStrictCompilerOptionEnabled(optionsStrict, "noImplicitThis"); // false
func IsStrongPrecedenceNode ¶
func IsSymbolDeclaredInFile ¶ added in v0.11.0
func IsSymbolDeclaredInFile(symbol *ast.Symbol, sf *ast.SourceFile) bool
IsSymbolDeclaredInFile reports whether the given symbol has at least one declaration in the specified source file. Use this to distinguish locally declared symbols (shadowed) from globals provided by lib.d.ts.
func IsSymbolFlagSet ¶
func IsSymbolFlagSet(symbol *ast.Symbol, flag ast.SymbolFlags) bool
func IsThenableType ¶
TODO(note): why there is no IntersectionTypeParts
func IsTrueLiteralType ¶
IsTrueLiteralType checks if the type is the boolean literal `true`. Handles both TypeFlagsBooleanLiteral (literal `true`) and TypeFlagsBoolean (widened boolean that is actually `true` from const narrowing).
func IsTypeAnyType ¶
func IsTypeFlagSetWithUnion ¶ added in v0.11.0
IsTypeFlagSetWithUnion checks type flags, iterating through union constituents. This matches typescript-eslint's isTypeFlagSet which aggregates union constituent flags.
func IsTypeParameter ¶
func IsTypeUnknownType ¶
func IsUnionType ¶
func IsUnsafeAssignment ¶
func IsUnsafeAssignment( t *checker.Type, receiverT *checker.Type, typeChecker *checker.Checker, senderNode *ast.Node, ) (receiver *checker.Type, sender *checker.Type, unsafe bool)
*
- Does a simple check to see if there is an any being assigned to a non-any type. *
- This also checks generic positions to ensure there's no unsafe sub-assignments.
- Note: in the case of generic positions, it makes the assumption that the two types are the same. *
- @example See tests for examples *
- @returns false if it's safe, or an object with the two types if it's unsafe
func IsVarKeyword ¶ added in v0.11.0
IsVarKeyword returns true if a VariableDeclarationList uses `var` (not `let`/`const`/`using`/`await using`).
func IsWriteReference ¶ added in v0.11.0
IsWriteReference checks if a node is a write reference (assignment target). This covers direct assignments, compound assignments, increment/decrement, destructuring patterns, and type assertion wrappers.
func Map ¶
func Map[T, U any](slice []T, f func(T) U) []U
Source: typescript-go/internal/core/core.go
func NaturalCompare ¶ added in v0.11.0
NaturalCompare compares two strings using natural sort order, where embedded numeric segments are compared by their numeric value (e.g., "a2" < "a10" instead of "a10" < "a2"). Returns -1 if a < b, 0 if a == b, 1 if a > b.
func NormalizeBigIntLiteral ¶
NormalizeBigIntLiteral normalizes a BigInt literal to its decimal string representation, matching ESLint's String(node.value) behavior. e.g., "1n" -> "1", "0x1n" -> "1", "0o1n" -> "1", "0b1n" -> "1"
func NormalizeNumericLiteral ¶
NormalizeNumericLiteral parses a numeric literal text and returns its normalized string representation, matching ESLint's String(node.value) behavior. e.g., "0x1" -> "1", "1.0" -> "1", "1e2" -> "100"
func ParseJSONC ¶
ParseJSONC parses JSONC (JSON with Comments) using hujson library
func StripJSONComments ¶
StripJSONComments removes comments from JSONC and returns clean JSON string
func ToStringSlice ¶ added in v0.11.0
func ToStringSlice(val interface{}) []string
ToStringSlice converts a weakly-typed JSON array ([]interface{}) to []string, extracting only the string elements. Returns nil if the input is nil, not an array, or contains no strings. Useful for parsing rule options from JSON config.
func TrimNodeTextRange ¶
func TrimmedNodeText ¶ added in v0.11.0
func TrimmedNodeText(sourceFile *ast.SourceFile, node *ast.Node) string
TrimmedNodeText returns the source text for node over the same span as TrimNodeTextRange.
func TypeMatchesSomeSpecifierWithCalleeNames ¶
func TypeMatchesSomeSpecifierWithCalleeNames( t *checker.Type, specifiers []TypeOrValueSpecifier, inlineSpecifiers []string, program *compiler.Program, calleeNames []string, ) bool
TypeMatchesSomeSpecifierWithCalleeNames is like TypeMatchesSomeSpecifier but also accepts callee names for matching export aliases (e.g., `export { test as it }` where the type's symbol name is "test" but the callee identifier is "it")
func VisitDestructuringIdentifiers ¶ added in v0.11.0
VisitDestructuringIdentifiers calls fn for each identifier target in a destructuring assignment pattern (object/array literal on the left side of an assignment expression). Handles shorthand properties, renamed properties, default values, rest/spread, and arbitrary nesting. This does NOT handle declaration-level destructuring (BindingPattern) — use CollectBindingNames for that.
Types ¶
type ConstraintTypeInfo ¶
type DiscriminatedAnyType ¶
type DiscriminatedAnyType uint8
const ( DiscriminatedAnyTypeAny DiscriminatedAnyType = iota DiscriminatedAnyTypePromiseAny DiscriminatedAnyTypeAnyArray DiscriminatedAnyTypeSafe )
func DiscriminateAnyType ¶
func DiscriminateAnyType( t *checker.Type, typeChecker *checker.Checker, program *compiler.Program, node *ast.Node, ) DiscriminatedAnyType
*
- @returns `DiscriminatedAnyTypeAny ` if the type is `any`, `DiscriminatedAnyTypeAnyArray` if the type is `any[]` or `readonly any[]`, `DiscriminatedAnyTypePromiseAny` if the type is `Promise<any>`,
* otherwise it returns `DiscriminatedAnyTypeSafe`.
type FunctionReturnAnalysis ¶
type FunctionReturnAnalysis struct {
EndReachable bool // Whether the function's end is reachable (can fall through without return/throw)
HasReturnWithValue bool // Whether any return statement returns a value
HasEmptyReturn bool // Whether any return statement is empty (return;)
}
FunctionReturnAnalysis holds the result of analyzing return behavior of a function.
func AnalyzeFunctionReturns ¶
func AnalyzeFunctionReturns(node *ast.Node) FunctionReturnAnalysis
AnalyzeFunctionReturns analyzes a function node's return behavior using the binder's control flow graph and ForEachReturnStatement. The node must be a function-like node (FunctionDeclaration, FunctionExpression, ArrowFunction, Constructor, MethodDeclaration, GetAccessor, SetAccessor).
The binder sets EndFlowNode on function bodies only when the function end is reachable (i.e., some code path falls through without returning or throwing). If EndFlowNode is nil and the body is present, all paths return or throw.
type MemberNameType ¶
type MemberNameType uint8
const ( MemberNameTypePrivate MemberNameType = iota MemberNameTypeQuoted MemberNameTypeNormal MemberNameTypeExpression )
func GetNameFromMember ¶
func GetNameFromMember(sourceFile *ast.SourceFile, member *ast.Node) (string, MemberNameType)
*
- Gets a string name representation of the name of the given MethodDefinition
- or PropertyDefinition node, with handling for computed property names.
type NameList ¶
type NameList []string
func (*NameList) UnmarshalJSON ¶
unmarshal a string or a list of strings to NameList
type OverlayVFS ¶
func (*OverlayVFS) DirectoryExists ¶
func (vfs *OverlayVFS) DirectoryExists(path string) bool
func (*OverlayVFS) FileExists ¶
func (vfs *OverlayVFS) FileExists(path string) bool
func (*OverlayVFS) GetAccessibleEntries ¶
func (vfs *OverlayVFS) GetAccessibleEntries(path string) (result vfs.Entries)
func (*OverlayVFS) ReadFile ¶
func (vfs *OverlayVFS) ReadFile(path string) (contents string, ok bool)
func (*OverlayVFS) Realpath ¶
func (vfs *OverlayVFS) Realpath(path string) string
func (*OverlayVFS) Remove ¶
func (vfs *OverlayVFS) Remove(path string) error
func (*OverlayVFS) UseCaseSensitiveFileNames ¶
func (vfs *OverlayVFS) UseCaseSensitiveFileNames() bool
func (*OverlayVFS) WalkDir ¶
func (vfs *OverlayVFS) WalkDir(root string, walkFn vfs.WalkDirFunc) error
type Set ¶
type Set[T comparable] struct { M map[T]struct{} }
func NewSetFromItems ¶
func NewSetFromItems[T comparable](items ...T) *Set[T]
func NewSetWithSizeHint ¶
func NewSetWithSizeHint[T comparable](hint int) *Set[T]
NewSetWithSizeHint creates a new Set with a hint for the number of elements it will contain.
type SyntacticError ¶
type SyntacticError struct {
Diagnostics []*ast.Diagnostic
// contains filtered or unexported fields
}
SyntacticError carries structured diagnostics for syntax errors. Callers can type-assert to access the raw diagnostics for rich rendering.
func (*SyntacticError) Error ¶
func (e *SyntacticError) Error() string
type TypeAwaitable ¶
type TypeAwaitable int32
const ( TypeAwaitableAlways TypeAwaitable = iota TypeAwaitableNever TypeAwaitableMay )
func NeedsToBeAwaited ¶
type TypeOrValueSpecifier ¶
type TypeOrValueSpecifier struct {
From TypeOrValueSpecifierFrom `json:"from"`
Name NameList `json:"name"`
// Can be used when From == TypeOrValueSpecifierFromFile
Path string `json:"path"`
// Can be used when From == TypeOrValueSpecifierFromPackage
Package string `json:"package"`
}
func (*TypeOrValueSpecifier) UnmarshalJSON ¶
func (s *TypeOrValueSpecifier) UnmarshalJSON(data []byte) error
UnmarshalJSON handles both string shorthand ("Promise") and object form ({"from": "lib", "name": "Promise"}) for TypeOrValueSpecifier, matching the original TypeScript-ESLint TypeOrValueSpecifier union type.
type TypeOrValueSpecifierFrom ¶
type TypeOrValueSpecifierFrom uint8
const ( TypeOrValueSpecifierFromFile TypeOrValueSpecifierFrom = iota TypeOrValueSpecifierFromLib TypeOrValueSpecifierFromPackage // TypeOrValueSpecifierFromString represents the string shorthand form. // It matches any type with the given name regardless of origin. TypeOrValueSpecifierFromString )
func (*TypeOrValueSpecifierFrom) UnmarshalJSON ¶
func (s *TypeOrValueSpecifierFrom) UnmarshalJSON(data []byte) error
unmarshal TypeOrValueSpecifierFrom from JSON string