utils

package
v0.22.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 15, 2026 License: MIT, MIT Imports: 35 Imported by: 0

Documentation

Overview

cspell:ignore octals

Index

Constants

View Source
const (
	// JSRegexOptions enables regexp2's ECMAScript mode for JavaScript RegExp
	// patterns that do not pass explicit flags.
	JSRegexOptions regexp2.RegexOptions = regexp2.ECMAScript
	// JSUnicodeRegexOptions mirrors `new RegExp(pattern, "u")`.
	JSUnicodeRegexOptions regexp2.RegexOptions = regexp2.ECMAScript | regexp2.Unicode
)

Variables

View Source
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 lint target discovery and fallback Program roots. Aligned with JS-side SCAN_EXCLUDE_DIRS: new Set(['node_modules', '.git']).

View Source
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

func AccessExpressionObject(node *ast.Node) *ast.Node

AccessExpressionObject returns the object expression of an access expression.

func AccessExpressionStaticName added in v0.11.0

func AccessExpressionStaticName(node *ast.Node) (string, bool)

AccessExpressionStaticName returns the static property name of an access expression (PropertyAccessExpression or ElementAccessExpression), or ("", false) if not static. Element access arguments are unwrapped through parentheses and TS assertions because ESTree-based helpers treat those wrappers as transparent.

func AddDefaultLibraryGlobals added in v0.22.0

func AddDefaultLibraryGlobals(dst map[string]bool, program *compiler.Program, typeChecker *checker.Checker)

AddDefaultLibraryGlobals adds value-space globals from the program's active TypeScript default libraries to dst. Symbols are collected from a default-lib source location so a same-named declaration in the linted module cannot hide the global from GetSymbolsInScope.

func AddECMAScriptGlobals added in v0.22.0

func AddECMAScriptGlobals(dst map[string]bool)

AddECMAScriptGlobals copies ECMAScript built-in global names into dst.

func AllHexDigits added in v0.15.1

func AllHexDigits(s string) bool

AllHexDigits reports whether s is non-empty and every byte is a hex digit.

func AreNodesStructurallyEqual added in v0.15.1

func AreNodesStructurallyEqual(a, b *ast.Node) bool

AreNodesStructurallyEqual reports whether two AST subtrees have identical syntactic shape and leaf values, transparently unwrapping ParenthesizedExpression on both sides at every level. Useful for rules that compare computed keys, duplicate case expressions, or any pattern that must be evaluated at the source-syntax level rather than by semantic reference identity (for which see IsSameReference).

Leaf comparison:

  • Identifier / PrivateIdentifier: `.Text` equality.
  • StringLiteral / NoSubstitutionTemplateLiteral / TemplateHead / Middle / Tail / RegularExpressionLiteral: textual equality.
  • NumericLiteral: normalized numeric value equality (e.g. `0x10` == `16`).
  • BigIntLiteral: normalized bigint value equality (e.g. `0x1n` == `1n`).
  • All other kinds (keyword tokens, punctuation tokens, composite nodes): Kind must match, and the non-nil children visited by ast.Node.ForEachChild must be pairwise structurally equal in order.

Comments and whitespace are not part of the AST and are therefore ignored (so `a+b` and `a + b` compare equal). Optional chaining IS preserved (`a.b` != `a?.b`). Type-only syntax (`as T`, `<T>x`, `x!`, `x satisfies T`) is compared as-is — callers that want to see through it should strip it first via ast.SkipOuterExpressions before calling this helper.

func BlockEndsWithTerminal added in v0.11.0

func BlockEndsWithTerminal(block *ast.Node) bool

BlockEndsWithTerminal checks if a block's last statement is a control flow terminal (break/return/throw/continue), possibly nested in inner blocks.

func BodyLikeRange added in v0.22.0

func BodyLikeRange(node *ast.Node) (int, int, bool)

BodyLikeRange returns the [pos, end) execution span for function-like and implicit scope-bearing nodes. Expressions in computed keys or decorators sit outside this span, so callers can attribute await/yield-like nodes to the enclosing runtime scope instead of the declaration they decorate.

func BracedNodeInnerRange added in v0.22.0

func BracedNodeInnerRange(sourceFile *ast.SourceFile, node *ast.Node) core.TextRange

BracedNodeInnerRange returns the span between a braced node's opening and closing braces. Callers should pass Block-like nodes whose trimmed text starts with "{" and ends with "}".

func CanBlockThrow added in v0.11.0

func CanBlockThrow(block *ast.Node) bool

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 CanTokenTextsBeAdjacent added in v0.22.0

func CanTokenTextsBeAdjacent(left string, right string) bool

CanTokenTextsBeAdjacent is a small source-text analogue of ESLint's astUtils.canTokensBeAdjacent. It returns false for token pairs that would merge into a different token if printed without whitespace.

func ClassEnd added in v0.22.0

func ClassEnd(pattern string, start int, flags RegexFlags) (int, bool)

ClassEnd returns the byte index just past the matching `]` for a class starting at `[` at pattern[start]. Handles escaped `]`, v-flag nested classes, and `\q{...}` which contains a literal `]` inside braces.

func CoerceInt added in v0.22.0

func CoerceInt(v any) (int, bool)

CoerceInt converts a JSON-decoded numeric value to int. JSON numbers come in as float64 from `encoding/json`, but rule_tester / test fixtures may pass raw int / int32 / int64 / float32, so accept all of them. Returns (value, true) on success, (0, false) for non-numeric inputs (including nil).

func CollectAllCallSignatures

func CollectAllCallSignatures(typeChecker *checker.Checker, t *checker.Type) []*checker.Signature

ex. getCallSignaturesOfType

func CollectBindingNames

func CollectBindingNames(nameNode *ast.Node, callback func(ident *ast.Node, name string))

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

func CollectProgramFiles(programs []*compiler.Program, fs vfs.FS, singleThreaded bool) map[string]struct{}

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 ComparePaths

func ComparePaths(a string, b string, program *compiler.Program) int

func CompileRegexp2 added in v0.22.0

func CompileRegexp2(pattern string, options regexp2.RegexOptions) (*regexp2.Regexp, error)

CompileRegexp2 compiles a regexp2 pattern with the caller's exact options. Use JSRegexOptions / JSUnicodeRegexOptions for ESLint rule options that model JavaScript RegExp patterns.

func ContainsLineTerminator added in v0.22.0

func ContainsLineTerminator(text string, low, high int) bool

ContainsLineTerminator reports whether the byte range `[low, high)` of `text` contains any ECMAScript LineTerminator (§12.3): LF (`\n`), CR (`\r`), LS (U+2028), or PS (U+2029).

Used by spacing rules to short-circuit "tokens on different lines" decisions equivalent to ESLint's `isTokenOnSameLine` helper. Out-of-range indices are clamped, and an empty range yields `false`.

LS and PS are encoded in UTF-8 as `E2 80 A8` and `E2 80 A9` respectively; detecting them via byte-level prefix `E2 80 A8`/`A9` is exactly as reliable as a rune scan and significantly faster on cold cache.

func CouldBeError added in v0.15.1

func CouldBeError(node *ast.Node) bool

CouldBeError reports whether a node could plausibly evaluate to an Error object at runtime. Mirrors ESLint's `astUtils.couldBeError`, adapted to the tsgo AST where AssignmentExpression / LogicalExpression / SequenceExpression are all flattened into BinaryExpression and ChainExpression has no analog.

Only parentheses are unwrapped — TS-only assertion wrappers (`x as T`, `<T>x`, `x satisfies T`, `x!`) are NOT unwrapped, because ESLint's `astUtils.couldBeError` does not list them and falls through to `false`. Verified against ESLint core run on a `.ts` file via `@typescript-eslint/parser`: `throw foo as Error;` and `throw foo!;` are both reported as "object".

Used by rules whose ESLint counterparts call `astUtils.couldBeError`: `no-throw-literal`, `prefer-promise-reject-errors`, etc.

func CreateCompilerHost

func CreateCompilerHost(cwd string, fs vfs.FS) compiler.CompilerHost

func CreateProgram

func CreateProgram(singleThreaded bool, fs vfs.FS, cwd string, tsconfigPath string, host compiler.CompilerHost) (*compiler.Program, error)

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 CreateProgramLenient added in v0.22.0

func CreateProgramLenient(singleThreaded bool, fs vfs.FS, cwd string, tsconfigPath string, host compiler.CompilerHost) (*compiler.Program, error)

CreateProgramLenient creates a tsconfig-backed Program but tolerates syntactic errors. CLI/API plain lint uses this so the final lint target set decides which syntax diagnostics are user-visible; type-check modes still report diagnostics from the tsconfig-backed Program boundary.

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 EnclosingVariableDeclarationOfBindingElement added in v0.22.0

func EnclosingVariableDeclarationOfBindingElement(bindingElement *ast.Node) *ast.Node

EnclosingVariableDeclarationOfBindingElement walks through nested BindingElement / BindingPattern layers to the containing VariableDeclaration.

func EslintLikePrecedence added in v0.22.0

func EslintLikePrecedence(node *ast.Node) int

EslintLikePrecedence returns a numeric precedence matching ESLint's astUtils.getPrecedence so behavior parity holds for tsgo nodes that ESLint classifies (e.g. ArrowFunction = 1, ConditionalExpression = 3). Returns -1 for TypeScript-only kinds (AsExpression, etc.) so the caller wraps them in parentheses defensively, matching ESLint's behavior on unknown node types.

func Every

func Every[T any](slice []T, f func(T) bool) bool

Source: typescript-go/internal/core/core.go

func ExtractRegexPatternAndFlags added in v0.11.0

func ExtractRegexPatternAndFlags(text string) (pattern string, flags string)

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 Filter

func Filter[T any](slice []T, f func(T) bool) []T

Source: typescript-go/internal/core/core.go

func FilterIndex

func FilterIndex[T any](slice []T, f func(T, int, []T) bool) []T

Source: typescript-go/internal/core/core.go

func FindEnclosingScope added in v0.11.0

func FindEnclosingScope(node *ast.Node) *ast.Node

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 Flatten

func Flatten[T any](array [][]T) []T

Source: typescript-go/internal/core/core.go

func ForEachComment

func ForEachComment(node *ast.Node, callback func(comment *ast.CommentRange), sourceFile *ast.SourceFile)

Port https://github.com/JoshuaKGoldberg/ts-api-utils/blob/491c0374725a5dd64632405efea101f20ed5451f/src/comments.ts#L37C17-L37C31

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

func ForEachToken(node *ast.Node, callback func(token *ast.Node), sourceFile *ast.SourceFile)

Port https://github.com/JoshuaKGoldberg/ts-api-utils/blob/491c0374725a5dd64632405efea101f20ed5451f/src/tokens.ts#L34

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 GetCallSignatures(typeChecker *checker.Checker, t *checker.Type) []*checker.Signature

func GetChildren

func GetChildren(node *ast.Node, sourceFile *ast.SourceFile) []*ast.Node

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 GetConstrainedTypeAtLocation

func GetConstrainedTypeAtLocation(typeChecker *checker.Checker, node *ast.Node) *checker.Type

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 GetConstructSignatures(typeChecker *checker.Checker, t *checker.Type) []*checker.Signature

func GetContextualType

func GetContextualType(
	typeChecker *checker.Checker,
	node *ast.Node,
) *checker.Type

*

  • 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 GetDeclListForSymbolDecl added in v0.22.0

func GetDeclListForSymbolDecl(decl *ast.Node) *ast.Node

GetDeclListForSymbolDecl returns the VariableDeclarationList associated with a declaration node, or nil if the declaration is not a variable-like binding.

func GetDeclaration

func GetDeclaration(
	typeChecker *checker.Checker,
	node *ast.Node,
) *ast.Declaration

GetDeclaration returns the first declaration of the symbol at `node`.

Returns nil when `typeChecker` or `node` is nil. Rules with optional type info (those that do not set `RequiresTypeInfo: true`) are scheduled with a nil TypeChecker on "gap files" — files in the program but not in `typeInfoFiles` (see internal/linter/linter.go). Rather than requiring every caller to nil-guard manually, this helper degrades gracefully: no checker → no declaration → caller falls back to structural checks. The `node == nil` guard mirrors the same convention already used by `GetReferenceSymbol` in shadowing.go.

func GetDeclarationIdentifier added in v0.11.0

func GetDeclarationIdentifier(decl *ast.Node) *ast.Node

GetDeclarationIdentifier returns the name node of a declaration.

func GetEnumLiterals

func GetEnumLiterals(t *checker.Type) []*checker.Type

*

  • 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

func GetEnumTypes(
	typeChecker *checker.Checker,
	t *checker.Type,
) []*checker.Type

*

  • 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

func GetForStatementHeadLoc(
	sourceFile *ast.SourceFile,
	node *ast.Node,
) core.TextRange

*

  • 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

func GetFunctionHeadLoc(sourceFile *ast.SourceFile, node *ast.Node) core.TextRange

*

  • 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 GetFunctionNameWithKind added in v0.22.0

func GetFunctionNameWithKind(node *ast.Node) string

GetFunctionNameWithKind mirrors ESLint's astUtils.getFunctionNameWithKind. It produces a human-readable description of the function used in diagnostic messages (e.g., `"function 'foo'"`, `"static private method '#bar'"`, `"arrow function"`, `"constructor"`). Modifier order matches ESLint: static, private, async, generator, then the function-kind keyword.

For nameless function-likes, walks the parent (VariableDeclaration, PropertyAssignment, PropertyDeclaration, PropertySignature, TypeAliasDeclaration) to recover the binding name where ESLint does the same via its `getName` / `getOuterName` helpers.

For a FunctionExpression assigned as the value of an object literal property (`var obj = { foo: function () {} }`), classifies the node as a "method" — ESTree models that case via `Property.value === FunctionExpression` and ESLint's classifier emits "method"; tsgo only collapses method-shorthand (`{ foo() {} }`) into MethodDeclaration, so we recover the same description from the parent.

Callers that need the upper-cased form (e.g., as the leading {{name}} placeholder of a sentence) should apply UpperCaseFirstASCII — this helper returns the lower-cased form to keep call sites simple.

func GetFunctionNameWithKindCore added in v0.22.0

func GetFunctionNameWithKindCore(node *ast.Node) string

GetFunctionNameWithKindCore mirrors ESLint core's astUtils.getFunctionNameWithKind. It intentionally does not walk from a function expression or arrow function to an enclosing variable declaration when resolving names. Core rules such as complexity and max-params rely on that narrower behavior for message text.

func GetHeritageClauses

func GetHeritageClauses(node *ast.Node) *ast.NodeList

func GetImportBindingNodes added in v0.11.0

func GetImportBindingNodes(node *ast.Node) []*ast.Node

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 GetNumberIndexType(typeChecker *checker.Checker, t *checker.Type) *checker.Type

func GetOptionsMap

func GetOptionsMap(opts any) map[string]interface{}

func GetOptionsString added in v0.11.0

func GetOptionsString(opts any) string

GetOptionsString extracts a string option from the weakly-typed options parameter. It handles both direct string format ("value") and array format (["value"]).

func GetParentFunctionNode

func GetParentFunctionNode(
	node *ast.Node,
) *ast.Node

func GetPropertyDisplayName added in v0.22.0

func GetPropertyDisplayName(name *ast.Node) string

GetPropertyDisplayName resolves a property-name node to the diagnostic name ESLint emits for statically-known member keys. Private identifiers keep their leading "#"; dynamic computed keys return "".

func GetPropertyInfo

func GetPropertyInfo(sourceFile *ast.SourceFile, node *ast.Node) (*ast.Node, string)

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 GetReferenceSymbol added in v0.15.1

func GetReferenceSymbol(node *ast.Node, typeChecker *checker.Checker) *ast.Symbol

GetReferenceSymbol returns the variable symbol for the given identifier. When the identifier is a shorthand property name or a local export specifier name, it returns the local value-binding symbol rather than the property or export symbol that `GetSymbolAtLocation` would otherwise produce.

func GetStaticExpressionValue added in v0.11.0

func GetStaticExpressionValue(node *ast.Node) (string, bool)

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

func GetStaticPropertyName(nameNode *ast.Node) (string, bool)

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 GetStaticStringLiteralValue added in v0.22.0

func GetStaticStringLiteralValue(node *ast.Node) (string, bool)

GetStaticStringLiteralValue returns the string value and a presence flag if node is a string literal or a no-substitution template literal. It does not unwrap parentheses or TS assertions; callers choose which wrappers are transparent for their rule.

func GetStaticStringValue added in v0.11.0

func GetStaticStringValue(node *ast.Node) string

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 GetThisExpression

func GetThisExpression(
	node *ast.Node,
) *ast.Node

func GetTypeName

func GetTypeName(
	typeChecker *checker.Checker,
	t *checker.Type,
) string

*

  • 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 GetVarDeclListKind added in v0.22.0

func GetVarDeclListKind(node *ast.Node) string

GetVarDeclListKind returns the kind keyword for a VariableDeclarationList: "var", "let", "const", "using", "await using", or "" if the node is not a VariableDeclarationList. Uses tsgo's IsVar* helpers (which apply GetCombinedNodeFlags and correctly handle the `NodeFlagsConst|NodeFlagsUsing` encoding of `await using`). Centralizes what was duplicated across no-var, prefer-const, no-loop-func, and one-var.

func GetVarKeywordRange added in v0.22.0

func GetVarKeywordRange(node *ast.Node, sourceFile *ast.SourceFile) core.TextRange

GetVarKeywordRange returns the range of the kind keyword (`var`/`let`/`const`/ `using` or `await` for `await using`) inside a VariableStatement or VariableDeclarationList. For VariableStatement it skips the modifier list (e.g. `export`/`declare`) so the returned range starts at the actual kind keyword. Used by rules that synthesize fixes around the kind keyword (one-var, no-var, prefer-const, etc.).

func GetVariableDeclarationSymbol added in v0.22.0

func GetVariableDeclarationSymbol(varDecl *ast.Node, typeChecker *checker.Checker) *ast.Symbol

GetVariableDeclarationSymbol returns the declared variable symbol for a VariableDeclaration. The declaration node's symbol is the closest match to ESLint's getDeclaredVariables(); GetSymbolAtLocation is only a fallback for older checker states where the declaration symbol was not attached.

func GetWellKnownSymbolPropertyOfType

func GetWellKnownSymbolPropertyOfType(t *checker.Type, name string, typeChecker *checker.Checker) *ast.Symbol

func HasCommentInSpan added in v0.22.0

func HasCommentInSpan(sourceFile *ast.SourceFile, start int, end int) bool

HasCommentInSpan reports whether any parsed comment overlaps the half-open source span [start, end). Unlike HasCommentsInRange, this scans the whole file's comment table, so callers can use it for ESLint-style commentsExistBetween checks over arbitrary token gaps.

func HasCommentInsideNode added in v0.22.0

func HasCommentInsideNode(sourceFile *ast.SourceFile, node *ast.Node) bool

HasCommentInsideNode reports whether node contains a real line or block comment. It walks parser-owned tokens, so comment-like text inside strings, templates, or regex literals is ignored.

func HasCommentsInRange

func HasCommentsInRange(sourceFile *ast.SourceFile, inRange core.TextRange) bool

func HasHoistedVarDeclaration added in v0.11.0

func HasHoistedVarDeclaration(node *ast.Node, name string) bool

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

func HasLocalDeclarationInStatements(statements []*ast.Node, name string) bool

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

func HasNameInBindingPattern(pattern *ast.Node, name string) bool

HasNameInBindingPattern checks if a binding pattern (including nested destructuring) contains a binding with the given name.

func HasNonEmptyFunctionBody added in v0.22.0

func HasNonEmptyFunctionBody(node *ast.Node) bool

HasNonEmptyFunctionBody reports whether a function-like node has executable body content. Expression-bodied arrows count as non-empty; empty blocks and body-less declarations do not.

func HasSameTokens added in v0.15.1

func HasSameTokens(sourceFile *ast.SourceFile, a, b *ast.Node) bool

HasSameTokens reports whether two nodes produce the same token stream when viewed at the raw-source level — matching ESLint's `sourceCode.getTokens(a)` vs `sourceCode.getTokens(b)` semantics, which preserves the original source form of each literal. Unlike AreNodesStructurallyEqual, this helper distinguishes:

  • `'a'` vs `"a"` (different quote style)
  • `0x1` vs `1` (different numeric source form)
  • `1n` vs `0x1n` (different bigint source form)
  • `1e2` vs `100` / `1.0` vs `1`

Implementation: we recurse on the AST using ast.SkipParentheses and ast.Node.ForEachChild. At leaf nodes (no children — identifiers, literals, keyword tokens) we compare the raw source slice via scanner.GetSourceTextOfNodeFromSourceFile. For composite nodes we recurse on children pairwise AND scan the "gaps" between children (and before/after the first/last child) with scanner.Scanner to pick up punctuation, keyword tokens, and operators that tsgo's ForEachChild does not visit — `(` `)` `,` `.` between children of a CallExpression, the `+`/`-` operator of a PrefixUnaryExpression, the `new`/`import` keyword of a MetaProperty, and so on. Whitespace and comments in a gap are trivia (scanner skips them), so the comparison is whitespace-insensitive exactly like ESLint's `getTokens`.

Parens: stripped once at the top level (matches ESLint / ESTree, where outer parens wrapping an operand aren't nodes and their tokens fall outside the operand's range). Parens INSIDE a compound expression — e.g. `(x).y` — ARE visible tokens in ESLint's view, and preserved here by the recursion not calling SkipParentheses again.

Templates: TemplateExpression / TemplateSpan children already cover the whole template source range contiguously, so the gap between any two children inside a template is empty. This means gap scanning never enters template-expression context and thus never needs the scanner's `ReScanTemplateToken` (which isn't exposed through the shim).

Use this helper when porting an ESLint rule whose oracle is token-level equality (e.g. `no-self-compare`'s `hasSameTokens`); use AreNodesStructurallyEqual when the rule's oracle is structural AST equality and literal-form / trivia differences should NOT matter (e.g. duplicate case detection).

func HasShadowingDeclaration added in v0.11.0

func HasShadowingDeclaration(node *ast.Node, name string) bool

HasShadowingDeclaration checks if a block contains a variable, function, class, enum, or namespace declaration whose name matches the given name.

func HasShadowingParameter added in v0.11.0

func HasShadowingParameter(node *ast.Node, name string) bool

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

func HasUseStrictDirective(block *ast.Node) bool

HasUseStrictDirective checks if a block or source file starts with a "use strict" directive.

func HasVarDeclListWithName added in v0.11.0

func HasVarDeclListWithName(node *ast.Node, name string) bool

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 IntersectionTypeParts

func IntersectionTypeParts(t *checker.Type) []*checker.Type

func IsAnyBuiltinSymbolLike

func IsAnyBuiltinSymbolLike(
	program *compiler.Program,
	typeChecker *checker.Checker,
	t *checker.Type,
) bool

func IsArgumentOfSpecificCall added in v0.15.1

func IsArgumentOfSpecificCall(node *ast.Node, index int, objectName, methodName string) bool

IsArgumentOfSpecificCall reports whether `node` sits at argument position `index` of a call to `<objectName>.<methodName>(...)` — covering optional chaining and parenthesized callee expressions, e.g. `(Object?.defineProperty)(...)`. This is the common shape for detecting property-descriptor arguments in `Object.defineProperty` / `Reflect.defineProperty`, mutation targets in `Object.assign`, and similar well-known API calls.

func IsArrayMethodCallWithPredicate

func IsArrayMethodCallWithPredicate(
	typeChecker *checker.Checker,
	node *ast.CallExpression,
) bool

func IsBindingPatternInAssignment added in v0.11.0

func IsBindingPatternInAssignment(node *ast.Node) bool

IsBindingPatternInAssignment checks if a binding pattern is the left side of an assignment.

func IsBooleanLiteralType

func IsBooleanLiteralType(t *checker.Type) bool

func IsBuiltinSymbolLike

func IsBuiltinSymbolLike(
	program *compiler.Program,
	typeChecker *checker.Checker,
	t *checker.Type,
	symbolNames ...string,
) bool

func IsBuiltinSymbolLikeRecurser

func IsBuiltinSymbolLikeRecurser(
	program *compiler.Program,
	typeChecker *checker.Checker,
	t *checker.Type,
	predicate func(subType *checker.Type) builtinPredicateMatches,
) bool

func IsBuiltinTypeAliasLike

func IsBuiltinTypeAliasLike(
	program *compiler.Program,
	typeChecker *checker.Checker,
	t *checker.Type,
	predicate func(subType *checker.Type) bool,
) bool

func IsCallback

func IsCallback(
	typeChecker *checker.Checker,
	param *ast.Symbol,
	node *ast.Node,
) bool

func IsCallee added in v0.11.0

func IsCallee(node *ast.Node) bool

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 IsConstructorName added in v0.15.1

func IsConstructorName(name string) bool

IsConstructorName reports whether `name` follows the ESLint constructor naming convention: the first character that is not `_`, `$`, or an ASCII digit is uppercase. Names consisting only of `_`, `$` and ASCII digits (e.g. `_`, `$$`, `_8`) are not treated as constructors.

Matches the `isConstructor` helper used by ESLint's `new-cap` and `object-shorthand` rules, including Unicode identifier characters (e.g. `Π`). ESLint's regex `/[^_$0-9]/u` pairs an ASCII-only digit range with a Unicode-aware `toUpperCase()` check — we mirror that: the digit prefix is strictly ASCII while the case test is `unicode.IsUpper`.

func IsDeclarationIdentifier added in v0.11.0

func IsDeclarationIdentifier(node *ast.Node) bool

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

func IsDefaultThisBinding(node *ast.Node) bool

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 IsDefaultValueInDestructuringAssignment added in v0.22.0

func IsDefaultValueInDestructuringAssignment(node *ast.Node) bool

IsDefaultValueInDestructuringAssignment checks whether node is a BinaryExpression(=) used as a default value inside a destructuring assignment target, such as `x = 5` in `[x = 5] = values` or `y = 5` in `({x: y = 5} = value)`.

func IsDirectivePrologueStatement added in v0.22.0

func IsDirectivePrologueStatement(node *ast.Node) bool

IsDirectivePrologueStatement reports whether node is a leading string-literal expression statement in a Program, function body, or TS module block.

func IsDirectivePrologueStatementIncludingClassStaticBlocks added in v0.22.0

func IsDirectivePrologueStatementIncludingClassStaticBlocks(node *ast.Node) bool

IsDirectivePrologueStatementIncludingClassStaticBlocks matches the @typescript-eslint/parser static-block behavior used by its extension rule.

func IsDisallowedUnusedExpression added in v0.22.0

func IsDisallowedUnusedExpression(node *ast.Node, opts NoUnusedExpressionOptions) bool

IsDisallowedUnusedExpression mirrors the no-unused-expressions checker: true means the expression has no accepted side effect and should be reported. This is rule semantics, not a general-purpose purity predicate.

func IsECMABlankLine added in v0.22.0

func IsECMABlankLine(s string) bool

IsECMABlankLine reports whether s contains only ECMAScript WhiteSpace / LineTerminator runes — matching JavaScript's `"".trim() === ""` check used by rules like max-lines / max-lines-per-function for `skipBlankLines`. Go's strings.TrimSpace diverges on U+FEFF (BOM) and U+0085 (NEL), so we can't use it directly.

func IsECMAScriptGlobal added in v0.22.0

func IsECMAScriptGlobal(name string) bool

IsECMAScriptGlobal reports whether name is an ECMAScript built-in global.

func IsErrorLike

func IsErrorLike(
	program *compiler.Program,
	typeChecker *checker.Checker,
	t *checker.Type) bool

*

  • @example
  • ```ts
  • class Foo extends Error {}
  • new Foo()
  • // ^ ErrorLike
  • ```

func IsFalseLiteralType

func IsFalseLiteralType(t *checker.Type) bool

IsFalseLiteralType checks if the type is the boolean literal `false`.

func IsFunctionEndReachable

func IsFunctionEndReachable(node *ast.Node) bool

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 IsFunctionLikeContainer added in v0.22.0

func IsFunctionLikeContainer(node *ast.Node) bool

IsFunctionLikeContainer reports whether node introduces a new function scope. Covers function declarations/expressions, arrow functions, methods, getters, setters, and constructors. Use this to stop traversals at function boundaries.

func IsGlobalParseIntCallee added in v0.22.0

func IsGlobalParseIntCallee(callee *ast.Node, globals map[string]bool) bool

IsGlobalParseIntCallee reports whether callee references the built-in `parseInt` or `Number.parseInt` function. It mirrors ESLint's astUtils.isSpecificId / isSpecificMemberAccess shape: outer parentheses and optional chaining are transparent, TS-only assertion wrappers are not.

globals is the config-declared `languageOptions.globals` / `/* global */` set (ctx.Globals); when it explicitly turns the referenced name `off`, the identifier no longer resolves to a known global and this returns false. Pass nil to skip that check (e.g. for callers whose upstream ESLint rule doesn't consult scope at all).

func IsHexDigit added in v0.15.1

func IsHexDigit(b byte) bool

IsHexDigit reports whether b is an ASCII hex digit (0-9, a-f, A-F). Exposed for rules that do their own pattern scanning.

func IsHigherPrecedenceThanAwait

func IsHigherPrecedenceThanAwait(node *ast.Node) bool

func IsInAmbientContext added in v0.22.0

func IsInAmbientContext(node *ast.Node) bool

IsInAmbientContext reports whether node was parsed inside an ambient context. TypeScript-Go propagates this through declaration files and `declare` contexts via NodeFlagsAmbient.

func IsInDestructuringAssignment added in v0.11.0

func IsInDestructuringAssignment(node *ast.Node) bool

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

func IsInObjectLiteralMethod(functionNode *ast.Node) bool

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 IsIntersectionType(t *checker.Type) bool

func IsIntrinsicErrorType

func IsIntrinsicErrorType(t *checker.Type) bool

func IsIntrinsicType

func IsIntrinsicType(t *checker.Type) bool

func IsIntrinsicVoidType

func IsIntrinsicVoidType(t *checker.Type) bool

func IsNameShadowedBetween added in v0.15.1

func IsNameShadowedBetween(node *ast.Node, boundary *ast.Node, name string) bool

IsNameShadowedBetween walks from `node` up to (but not including) `boundary`, returning true if any intermediate scope introduces a binding for `name`.

Scopes examined:

  • Function-like parameter lists (covers all 7 function-like kinds).
  • Function expression names and hoisted `var` declarations in function bodies.
  • Block-scoped declarations (var/let/const/function/class inside a Block).
  • Catch-clause variable bindings (including destructured patterns).
  • For-statement `let`/`const` init (scoped to the loop).
  • For-in / for-of `let`/`const` init (scoped to the loop).
  • Class declaration/expression names (scoped to the class body).
  • Enum declaration names.

Use this when a rule tracks a specific declaration (e.g. a parameter, class, or function name) and needs to ignore references that were shadowed before they reached the declaration site. For scope walks that should also examine the SourceFile or module boundary, use `IsShadowed` instead.

func IsNonReferenceIdentifier added in v0.11.0

func IsNonReferenceIdentifier(node *ast.Node) bool

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

func IsNullLiteral(node *ast.Node) bool

IsNullLiteral checks if a node is the null keyword, unwrapping parentheses.

func IsNullOrUndefined added in v0.11.0

func IsNullOrUndefined(node *ast.Node) bool

IsNullOrUndefined checks if a node is a null literal, undefined identifier, or void expression, unwrapping parentheses.

func IsNullableType added in v0.11.0

func IsNullableType(t *checker.Type) bool

IsNullableType checks if the type includes null, undefined, void, any or unknown. This matches typescript-eslint's isNullableType utility.

func IsNumberLiteralZeroOrNaN added in v0.15.1

func IsNumberLiteralZeroOrNaN(val interface{}) bool

IsNumberLiteralZeroOrNaN checks if a number literal type value is 0 or NaN. tsgo stores number literal values as a named float64 type, so we use ValueToString for reliable string conversion and then parse.

func IsObjectType

func IsObjectType(t *checker.Type) bool

func IsParenlessArrowFunction

func IsParenlessArrowFunction(node *ast.Node) bool

func IsPlusBinaryExpression added in v0.15.1

func IsPlusBinaryExpression(node *ast.Node) bool

IsPlusBinaryExpression reports whether node is a `+` binary expression. Covers both string concatenation and numeric addition — callers that only care about concatenation must additionally inspect the operands.

func IsPossiblyFalsy added in v0.11.0

func IsPossiblyFalsy(t *checker.Type) bool

IsPossiblyFalsy checks if any union constituent of the type could be falsy.

func IsPossiblyTruthy added in v0.11.0

func IsPossiblyTruthy(t *checker.Type) bool

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

func IsPromiseLike(
	program *compiler.Program,
	typeChecker *checker.Checker,
	t *checker.Type) bool

*

  • @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 IsSameLine added in v0.22.0

func IsSameLine(sourceFile *ast.SourceFile, a int, b int) bool

IsSameLine reports whether two positions are on the same ECMAScript line.

func IsSameReference added in v0.11.0

func IsSameReference(left, right *ast.Node) bool

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

func IsShadowed(node *ast.Node, name string) bool

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 IsSpecificMemberAccess added in v0.15.1

func IsSpecificMemberAccess(node *ast.Node, objectName, methodName string) bool

IsSpecificMemberAccess reports whether `node` is a member access of the form `<objectName>.<methodName>`. Both dot (`Object.defineProperty`) and bracket-with-static-string (`Object['defineProperty']`) forms are matched, each transparently unwrapping parentheses (e.g. `(Object).defineProperty`) and optional chaining (`Object?.defineProperty`, `Object?.['defineProperty']`). Mirrors ESLint's `astUtils.isSpecificMemberAccess`.

If `objectName` is the empty string, the object identity check is skipped — any expression on the left of the method is accepted — matching ESLint's behavior when the `objectName` argument is `null`.

func IsStartOfExpressionStatement added in v0.22.0

func IsStartOfExpressionStatement(sourceFile *ast.SourceFile, node *ast.Node) bool

IsStartOfExpressionStatement reports whether node starts an ancestor ExpressionStatement without crossing a ParenthesizedExpression.

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 IsStringLiteralOrTemplate added in v0.15.1

func IsStringLiteralOrTemplate(node *ast.Node) bool

IsStringLiteralOrTemplate reports whether node is a string literal or a template literal (with or without substitutions). Matches the semantics of ESLint's `astUtils.isStringLiteral`, which treats `Literal{string}` and `TemplateLiteral` as equivalent. The shim's `ast.IsStringLiteralLike` only covers `StringLiteral` and `NoSubstitutionTemplateLiteral`, so we also include `TemplateExpression` (templates with `${}`).

func IsStrongPrecedenceNode

func IsStrongPrecedenceNode(innerNode *ast.Node) bool

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 IsSymbolFromDefaultLibrary

func IsSymbolFromDefaultLibrary(
	program *compiler.Program,
	symbol *ast.Symbol,
) bool

func IsThenableType

func IsThenableType(
	typeChecker *checker.Checker,
	node *ast.Node,
	t *checker.Type,
) bool

TODO(note): why there is no IntersectionTypeParts

func IsThisVoidParameter added in v0.22.0

func IsThisVoidParameter(param *ast.Node) bool

IsThisVoidParameter reports whether param is TypeScript's synthetic `this: void` parameter. It delegates the `this` shape check to tsgo so callers do not need to duplicate identifier/name assumptions.

func IsTriviaWhitespaceByte added in v0.22.0

func IsTriviaWhitespaceByte(b byte) bool

IsTriviaWhitespaceByte reports whether `b` is one of the ASCII whitespace or line-terminator bytes recognized by ECMAScript §12.2 / §12.3:

U+0009 HT, U+000A LF, U+000B VT, U+000C FF, U+000D CR, U+0020 SP.

Used as the fast path for forward/reverse trivia scans on byte streams. For non-ASCII bytes (>= 0x80), the caller MUST decode the rune and fall back to IsTriviaWhitespaceRune — multi-byte UTF-8 sequences encode runes like NBSP (U+00A0) whose individual bytes are >= 0x80 and would be misread by a byte-only test.

func IsTriviaWhitespaceRune added in v0.22.0

func IsTriviaWhitespaceRune(r rune) bool

IsTriviaWhitespaceRune reports whether `r` is a non-ASCII whitespace or line-terminator rune recognized by ECMAScript:

  • WhiteSpace (§12.2): U+00A0 NBSP, U+FEFF ZWNBSP, plus any rune in Unicode `Space_Separator` (Zs) — U+1680 Ogham, U+2000–U+200A (En Quad through Hair Space), U+202F Narrow NBSP, U+205F Medium Mathematical Space, U+3000 Ideographic Space.
  • LineTerminator (§12.3): U+2028 LS, U+2029 PS.

Should ONLY be called for runes >= U+0080. The ASCII subset is handled by IsTriviaWhitespaceByte on the fast path.

Deliberately excluded — they are NOT matched by JS `\s` / ECMAScript WhiteSpace (verified empirically against V8 and ESLint with `/\s/`):

  • U+0085 Next Line: in Unicode `\p{White_Space}` but NOT in ES WhiteSpace (only specific allow-listed runes count).
  • U+200B Zero Width Space: category Cf (Format), not Zs; tsgo's scanner treats it as whitespace internally, but that's a TS-compiler quirk not ESLint behavior.

func IsTrueLiteralType

func IsTrueLiteralType(t *checker.Type) bool

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 IsTypeAnyArrayType

func IsTypeAnyArrayType(
	t *checker.Type,
	typeChecker *checker.Checker,
) bool

*

  • @returns true if the type is `any[]`

func IsTypeAnyType

func IsTypeAnyType(t *checker.Type) bool

func IsTypeFlagSet

func IsTypeFlagSet(t *checker.Type, flags checker.TypeFlags) bool

func IsTypeFlagSetWithUnion added in v0.11.0

func IsTypeFlagSetWithUnion(t *checker.Type, flags checker.TypeFlags) bool

IsTypeFlagSetWithUnion checks type flags, iterating through union constituents. This matches typescript-eslint's isTypeFlagSet which aggregates union constituent flags.

func IsTypeParameter

func IsTypeParameter(t *checker.Type) bool

func IsTypeReference added in v0.22.0

func IsTypeReference(t *checker.Type) bool

func IsTypeUnknownArrayType

func IsTypeUnknownArrayType(
	t *checker.Type,
	typeChecker *checker.Checker,
) bool

*

  • @returns true if the type is `unknown[]`

func IsTypeUnknownType

func IsTypeUnknownType(t *checker.Type) bool

func IsUndefinedIdentifier added in v0.15.1

func IsUndefinedIdentifier(node *ast.Node) bool

IsUndefinedIdentifier reports whether the node, after unwrapping parens, is the literal identifier `undefined`. Purely lexical — does not detect `void 0`, `undefined as any`, or a shadowed `undefined` binding, matching ESLint's `node.argument.name === "undefined"` check (which only sees an Identifier after parens are dropped at parse time, not after TS assertions).

func IsUnionType

func IsUnionType(t *checker.Type) bool

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 IsValidRegexLiteral added in v0.22.0

func IsValidRegexLiteral(literal string) bool

IsValidRegexLiteral reports whether literal is a complete ECMAScript RegExp literal, including leading/trailing slashes and flags, under tsgo's latest regex grammar. Use this before offering a fix that emits a regex literal.

func IsVarDeclInForInOrOf added in v0.22.0

func IsVarDeclInForInOrOf(varDecl *ast.Node) bool

IsVarDeclInForInOrOf reports whether a VariableDeclaration sits directly inside a for-in/for-of initializer.

func IsVarKeyword added in v0.11.0

func IsVarKeyword(node *ast.Node) bool

IsVarKeyword returns true if a VariableDeclarationList uses `var` (not `let`/`const`/`using`/`await using`).

func IsVariableWriteReference added in v0.22.0

func IsVariableWriteReference(node *ast.Node) bool

IsVariableWriteReference reports whether an identifier writes to its variable. It extends IsWriteReference with writes introduced by variable declarations with initializers, for-in/for-of declarations, and catch bindings, matching ESLint scope-manager write-reference semantics.

func IsWriteReference added in v0.11.0

func IsWriteReference(node *ast.Node) bool

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 IterateRegexCharacterClasses added in v0.15.1

func IterateRegexCharacterClasses(pattern string, flags RegexFlags, cb func(start, end int)) bool

IterateRegexCharacterClasses walks a regex pattern and invokes cb once per top-level character class (including any v-flag nested classes, at each nesting level). cb receives the byte range [start, end) covering `[`..`]`.

Returns false if the pattern is malformed (unterminated class, unterminated escape at EOF). When false, cb may have been invoked for classes encountered before the error.

func LineContentEnd added in v0.22.0

func LineContentEnd(text string, nextLineStart int) int

LineContentEnd returns the byte position just past the last character of the line whose successor starts at nextLineStart — i.e. nextLineStart with its immediately-preceding ECMA line terminator (LF, CR, CRLF, LS, PS) stripped. Useful when slicing a single line out of source text without its terminator, matching the behavior of ESLint's SourceCode.lines entries.

func Map

func Map[T, U any](slice []T, f func(T) U) []U

Source: typescript-go/internal/core/core.go

func Must

func Must[T any](v T, err error) T

func NaturalCompare added in v0.11.0

func NaturalCompare(a, b string) int

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 NeedsClassMemberLeadingSemicolon added in v0.22.0

func NeedsClassMemberLeadingSemicolon(
	sourceFile *ast.SourceFile,
	classNode *ast.Node,
	member *ast.Node,
	nextToken SourceToken,
	options ClassMemberLeadingSemicolonOptions,
) bool

NeedsClassMemberLeadingSemicolon reports whether an edit that removes or rewrites member would leave nextToken at the start of a class member in a position where the previous property declaration could consume it as part of its initializer or type.

func NeedsLeadingSpaceForReplacement added in v0.15.1

func NeedsLeadingSpaceForReplacement(src string, insertPos int, replacement string) bool

NeedsLeadingSpaceForReplacement reports whether inserting `replacement` at `insertPos` in `src` would merge with the preceding character into a single identifier token. Callers use this when synthesizing a fix whose text starts with an identifier (e.g. `Boolean(foo)`, `Number(foo)`, `String(foo)`) to decide whether a leading space is required.

Mirrors the identifier/keyword case of ESLint's `canTokensBeAdjacent`: `typeof+foo` replaced with `Number(foo)` would otherwise become `typeofNumber(foo)` (a single identifier). Multi-byte identifier chars are handled via `scanner.IsIdentifierPart` / `scanner.IsIdentifierStart`.

func NeedsPrecedingSemicolon added in v0.22.0

func NeedsPrecedingSemicolon(sourceFile *ast.SourceFile, node *ast.Node) bool

NeedsPrecedingSemicolon mirrors ESLint's common ASI check for fixes that make an expression-starter token begin a statement on a new line.

func NewOverlayVFS

func NewOverlayVFS(baseFS vfs.FS, virtualFiles map[string]string) vfs.FS

func NewOverlayVFSForFile

func NewOverlayVFSForFile(filePath string, source string) vfs.FS

func NormalizeBigIntLiteral

func NormalizeBigIntLiteral(text string) string

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

func NormalizeNumericLiteral(text string) string

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 ParseHexUint added in v0.15.1

func ParseHexUint(s string) uint32

ParseHexUint parses s as a hex number, returning 0 on empty/non-hex input.

func ParseJSONC

func ParseJSONC(data []byte, v interface{}) error

ParseJSONC parses JSONC (JSON with Comments) using hujson library

func Ref

func Ref[T any](a T) *T

SUPER DIRTY HACK FOR OPTIONAL FIELDS :(

func Regexp2MatchString added in v0.22.0

func Regexp2MatchString(re *regexp2.Regexp, s string) bool

Regexp2MatchString reports whether re matches s. regexp2 only returns an error for runtime failures such as timeouts, which lint rules treat as no match instead of reporting a diagnostic.

func ResolveLegacyMaxOption added in v0.22.0

func ResolveLegacyMaxOption(options any, defaultMax int) int

ResolveLegacyMaxOption resolves ESLint's legacy maximum/max option shape. It handles number forms (`3` / `[3]`) plus object forms (`{max: 3}` / `[{maximum: 3}]`). `maximum` wins only when it coerces to a non-zero number; otherwise `max` is used. If either key is present but neither yields a numeric threshold, ESLint ends up comparing against `undefined`, which never reports; MaxInt gives the same observable behavior in Go.

func SafeReplacementText added in v0.22.0

func SafeReplacementText(sourceFile *ast.SourceFile, node *ast.Node, replacement string) string

SafeReplacementText adds a single leading or trailing space when replacing node with replacement would otherwise merge with an adjacent token.

func SkipAssertionsAndParens added in v0.22.0

func SkipAssertionsAndParens(node *ast.Node) *ast.Node

SkipAssertionsAndParens strips parentheses and all TS assertion wrappers (as, satisfies, !, <T>) from an expression, mirroring ESLint's unwrapTSAsExpression(uncast(node)). Returns nil when node is nil so callers can safely pass optional AST fields such as an absent initializer.

func SkipLeadingWhitespace added in v0.22.0

func SkipLeadingWhitespace(text string, low, high int) int

SkipLeadingWhitespace walks forward from `low` through ECMAScript trivia whitespace and line terminators (the union of §12.2 WhiteSpace and §12.3 LineTerminator), returning the position of the first non-whitespace byte (or `high` if nothing but whitespace remains).

Counterpart to SkipTrailingWhitespace. tsgo's `scanner.SkipTriviaEx` also skips comments and conflict markers; this helper is purely whitespace + line-terminator, useful when callers need to handle comments / other tokens separately. ASCII bytes take the fast path; non-ASCII bytes decode via `utf8.DecodeRune` and dispatch to `IsTriviaWhitespaceRune`.

func SkipPatternEscape added in v0.22.0

func SkipPatternEscape(pattern string, i int, flags RegexFlags) (int, bool)

SkipPatternEscape returns how many bytes a `\`-prefixed escape consumes at pattern[i] (including the leading `\`) for the purposes of class-boundary scanning. Returns ok=false at EOF on `\`.

func SkipTrailingWhitespace added in v0.22.0

func SkipTrailingWhitespace(text string, low, high int) int

SkipTrailingWhitespace walks back from `high` through ECMAScript trivia whitespace and line terminators (the union of §12.2 WhiteSpace and §12.3 LineTerminator), returning the position one past the last non-whitespace byte (i.e. the end-exclusive of the last token in `[low, high)`). Returns `low` when nothing but whitespace remains.

tsgo exposes `scanner.SkipTriviaEx` for forward scanning only; this function is the missing reverse counterpart. ASCII bytes are handled on the fast path; non-ASCII bytes decode the rune via `utf8.DecodeLastRune` and dispatch to `IsTriviaWhitespaceRune`.

Does NOT skip block or line comments — callers that need to skip those (or recognize comment boundaries) must do it themselves. This mirrors `SkipTriviaEx`'s `StopAtComments: true` mode, where the forward scan also stops at the start of a comment.

func Some

func Some[T any](slice []T, f func(T) bool) bool

Source: typescript-go/internal/core/core.go

func StripJSONComments

func StripJSONComments(jsoncString string) string

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 TrimNodeTextRange(sourceFile *ast.SourceFile, node *ast.Node) core.TextRange

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 TypeMatchesSomeSpecifier

func TypeMatchesSomeSpecifier(
	t *checker.Type,
	specifiers []TypeOrValueSpecifier,
	inlineSpecifiers []string,
	program *compiler.Program,
) bool

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 TypeRecurser

func TypeRecurser(t *checker.Type, predicate func(t *checker.Type) bool) bool

func UnionTypeParts

func UnionTypeParts(t *checker.Type) []*checker.Type

func UpperCaseFirstASCII added in v0.22.0

func UpperCaseFirstASCII(s string) string

UpperCaseFirstASCII returns s with its first byte mapped to upper case if the byte is an ASCII lowercase letter; otherwise returns s unchanged. Sufficient for ESLint's `astUtils.upperCaseFirst` since all function-kind tokens are ASCII English ("function", "method", "constructor", …).

func VariableDeclarationIntroducesWrite added in v0.22.0

func VariableDeclarationIntroducesWrite(varDecl *ast.Node) bool

VariableDeclarationIntroducesWrite reports whether a VariableDeclaration's binding is written at introduction.

func VisitDestructuringIdentifiers added in v0.11.0

func VisitDestructuringIdentifiers(node *ast.Node, fn func(*ast.Node))

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.

func WithParseCache added in v0.22.0

func WithParseCache(host compiler.CompilerHost, cache *ParseCache) compiler.CompilerHost

WithParseCache wraps host with the shared parse cache. A nil cache returns the host unchanged, so callers need no branches. The cache must be created at the pipeline entry and passed down explicitly (I9) — never stored in a package-level singleton, which would silently leak sharing into unrelated paths (rule_tester, --api getAstInfo) and grow without bound in long-running processes.

Types

type ClassMemberLeadingSemicolonOptions added in v0.22.0

type ClassMemberLeadingSemicolonOptions struct {
	// IncludePropertiesWithoutInitializers also treats plain fields like `foo`
	// as hazards. Type-only fields like `foo: string` are always considered
	// because the trailing type can merge with a following computed member.
	IncludePropertiesWithoutInitializers bool
}

ClassMemberLeadingSemicolonOptions controls how NeedsClassMemberLeadingSemicolon treats class fields without initializers.

type Completion added in v0.22.0

type Completion int

Completion represents the control-flow completion kind of a statement.

const (
	CompletionFallsThrough Completion = iota // execution continues normally to the next statement
	CompletionTerminates                     // return / throw / process.exit terminates the function
	CompletionStops                          // break / continue exits the current loop or switch arm
)

func StatementCompletion added in v0.22.0

func StatementCompletion(stmt *ast.Node) Completion

StatementCompletion returns the control-flow completion of a single statement, recursively analyzing compound statements (if/try/switch/loops/labels). process.exit() and process.abort() are treated as CompletionTerminates.

func StatementListCompletion added in v0.22.0

func StatementListCompletion(statements []*ast.Node) Completion

StatementListCompletion returns the completion of executing a sequence of statements in order. It stops at the first non-FallsThrough statement.

type ConstraintTypeInfo

type ConstraintTypeInfo struct {
	ConstraintType  *checker.Type
	IsTypeParameter bool
}

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

func (s *NameList) UnmarshalJSON(data []byte) error

unmarshal a string or a list of strings to NameList

type NoUnusedExpressionOptions added in v0.22.0

type NoUnusedExpressionOptions struct {
	AllowShortCircuit    bool
	AllowTernary         bool
	AllowTaggedTemplates bool
	EnforceForJSX        bool
}

NoUnusedExpressionOptions contains the expression-shape switches shared by ESLint core and typescript-eslint's no-unused-expressions rules.

func ParseNoUnusedExpressionOptions added in v0.22.0

func ParseNoUnusedExpressionOptions(raw any) NoUnusedExpressionOptions

ParseNoUnusedExpressionOptions reads the shared ESLint-compatible options. ignoreDirectives only affects ESLint's legacy ecmaVersion: 3 mode, which rslint does not expose; directive prologues are always skipped.

type OverlayVFS

type OverlayVFS struct {
	VirtualFiles map[string]string
	// contains filtered or unexported fields
}

func (*OverlayVFS) AppendFile added in v0.22.0

func (vfs *OverlayVFS) AppendFile(path string, data string) error

func (*OverlayVFS) Chtimes

func (vfs *OverlayVFS) Chtimes(path string, atime time.Time, mtime time.Time) error

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) Stat

func (vfs *OverlayVFS) Stat(path string) vfs.FileInfo

func (*OverlayVFS) UseCaseSensitiveFileNames

func (vfs *OverlayVFS) UseCaseSensitiveFileNames() bool

func (*OverlayVFS) WalkDir

func (vfs *OverlayVFS) WalkDir(root string, walkFn vfs.WalkDirFunc) error

func (*OverlayVFS) WriteFile

func (vfs *OverlayVFS) WriteFile(path string, data string) error

type ParseCache added in v0.22.0

type ParseCache struct {
	// contains filtered or unexported fields
}

ParseCache owns two run/request-scoped cache layers shared across Programs: a source snapshot generation keyed by the compiler host's exact normalized file name, and an append-mostly parsed SourceFile cache keyed by every parse input. Multiple tsconfigs can therefore reuse both the source text/hash and the resulting *ast.SourceFile object.

The AST key reuses the upstream project.ParseCacheKey — SourceFileParseOptions (FileName + Path + ExternalModuleIndicatorOptions) + ScriptKind + an xxh3 hash of the file content. This is exactly the condition under which tsgo's own LSP shares SourceFile objects across projects (see typescript-go/internal/project/parsecache.go), so a cache hit is by construction equivalent to an independent parse of the same inputs.

Sharing is an optimization, never a correctness requirement: two Programs holding two distinct objects for the same file is the no-cache baseline. That is what makes RetainOnly's deletion-only eviction safe (see I8 below).

Invariants (enforced here, relied on by callers):

I1: within one source generation, the first successful read of an exact
    FileName is authoritative. Lexical/canonical/symlink/case aliases are
    never merged. Failed reads are not stored.
I2: a source snapshot publishes immutable text and its xxh3 hash as one
    value. The exact same text/hash pair is used to key and build the AST.
I3: file.Hash is never written. The --api EncodeAST header encodes
    sourceFile.Hash (bytes 4-19) and is all-zero today; writing it
    would change encoded output bytes.
I4: concurrent source and AST misses resolve via LoadOrStore. Every loser
    uses the published winner; duplicate cold reads/parses may occur, but
    callers within a generation observe one winning snapshot/AST per key.
I5: the source layer owned by one cache binds to one exact pointer-identity
    FS across its generations. Hosts backed by another or a non-pointer FS
    bypass only the source layer and still use the content-keyed AST cache.
I6: ScriptKind is derived exactly like the default compiler host.
I7: source invalidation atomically swaps in a fresh generation. It never
    clears a live map, so a pre-invalidation miss can only publish into its
    captured old generation. Invalidation is not a reader barrier.
I8: AST eviction is deletion-only (RetainOnly). A deleted entry is simply
    re-parsed on next request; selective rewriting of entries is
    forbidden — deletion can cost a parse, never a stale result.
I9: cache ownership is explicit and bounded to one CLI run or API request;
    no package-level singleton may extend source/AST lifetime implicitly.

func NewParseCache added in v0.22.0

func NewParseCache() *ParseCache

NewParseCache returns a fresh cache, or nil (disabling caching entirely via the WithParseCache nil-passthrough) when RSLINT_DISABLE_PARSE_CACHE is set. The escape hatch is undocumented — it exists for bisecting user issues and A/B verification, not as a user-facing knob.

func (*ParseCache) InvalidateSourceSnapshots added in v0.22.0

func (c *ParseCache) InvalidateSourceSnapshots()

InvalidateSourceSnapshots atomically installs an empty source generation. Lookups that already captured the previous generation may finish against it; subsequent lookups use the new generation. The AST cache is intentionally retained because unchanged content can still reuse its parsed SourceFile.

func (*ParseCache) RetainOnly added in v0.22.0

func (c *ParseCache) RetainOnly(programs []*compiler.Program)

RetainOnly evicts every entry whose SourceFile is not referenced by any of the given programs (live set = union of all GetSourceFiles() pointers, including gap-fallback programs). One sweep reclaims both --fix intermediate versions (old-hash objects absent from rebuilt programs) and build-time dedup losers (parsed but never included in a program). Deletion-only per I8: an evicted entry that is requested again is re-parsed into a fresh object, which is the no-cache baseline behavior. Source snapshots have a separate generation lifetime and are not pruned here.

type ProgramSourceLookup added in v0.22.0

type ProgramSourceLookup struct {
	// contains filtered or unexported fields
}

ProgramSourceLookup resolves a filesystem target to the exact source file in one Program. Its canonical source index is built lazily and lives only for the lookup's owning lint operation.

func NewProgramSourceLookup added in v0.22.0

func NewProgramSourceLookup(program *compiler.Program, fs vfs.FS) *ProgramSourceLookup

NewProgramSourceLookup creates an exact source lookup for one Program.

func (*ProgramSourceLookup) CanonicalSourceFile added in v0.22.0

func (lookup *ProgramSourceLookup) CanonicalSourceFile(canonicalPath string) *ast.SourceFile

CanonicalSourceFile finds a Program source by physical filesystem identity. The index is created only after direct candidate lookups miss.

func (*ProgramSourceLookup) SourceFileForCandidate added in v0.22.0

func (lookup *ProgramSourceLookup) SourceFileForCandidate(candidate string, canonicalTarget string) *ast.SourceFile

SourceFileForCandidate validates a Program lookup against the target's exact canonical identity. This rejects a case-folded lookup that returned a different physical file.

func (*ProgramSourceLookup) SourceFileForPath added in v0.22.0

func (lookup *ProgramSourceLookup) SourceFileForPath(filePath string) *ast.SourceFile

SourceFileForPath resolves a lexical filesystem path through exact and canonical Program source identities.

type ReferenceIndex added in v0.22.0

type ReferenceIndex struct {
	// contains filtered or unexported fields
}

ReferenceIndex wraps TypeScript-Go's per-symbol reference lookup and keeps a small name index only for checker edge cases where symbol identity differs from ESLint scope-manager's local variable identity.

func NewReferenceIndex added in v0.22.0

func NewReferenceIndex(sourceFile *ast.SourceFile, typeChecker *checker.Checker) *ReferenceIndex

func (*ReferenceIndex) ForEachReference added in v0.22.0

func (i *ReferenceIndex) ForEachReference(sym *ast.Symbol, cb func(*ast.Node) bool)

ForEachReference invokes cb for every identifier node resolving to sym, in source order. It returns early when cb returns true.

func (*ReferenceIndex) ForEachReferenceByName added in v0.22.0

func (i *ReferenceIndex) ForEachReferenceByName(name string, boundary *ast.Node, cb func(*ast.Node) bool)

ForEachReferenceByName invokes cb for identifier references with the given text that are not shadowed between the reference site and boundary. This is a fallback for TypeScript checker cases where a local declaration collides with a lib/global symbol and symbol identity no longer matches ESLint's scope-manager variable identity.

type RegexCharElement added in v0.15.1

type RegexCharElement struct {
	Kind            RegexCharElementKind
	Value           uint32
	IsUBrace        bool
	IsLoneSurrogate bool

	Max         uint32
	MaxIsUBrace bool

	Start int
	End   int
}

RegexCharElement is one element of a parsed character class body.

For RegexCharSingle:

  • Value holds the element's effective value (UTF-16 code unit or the astral code point when combined via `\uHHHH\uHHHH` under u/v).
  • IsUBrace is true iff the element was written as `\u{H...}`.
  • IsLoneSurrogate is true iff the element is a lone surrogate from a raw astral character under non-u mode (where regexpp sees it as two units).

For RegexCharRange:

  • Value / IsUBrace describe the `a` endpoint.
  • Max / MaxIsUBrace describe the `b` endpoint.

For RegexCharBreaker:

  • Value, Max, IsUBrace are unused.

Start / End are byte offsets within the pattern text covering the element's source extent.

func ParseRegexCharacterClass added in v0.15.1

func ParseRegexCharacterClass(pattern string, start int, flags RegexFlags) ([]RegexCharElement, int, bool)

ParseRegexCharacterClass parses a character class starting at pattern[start] (which must be `[`). It returns the flat element list (ranges expanded into min/max; nested classes and set operators emitted as breakers at the position where they appear) and the byte index just past the closing `]`.

The input range [start, end) is trusted to be well-formed (e.g. from a prior call to IterateRegexCharacterClasses).

Note: nested v-flag classes themselves are not recursed into by this function — they appear only as RegexCharBreaker. Callers that want to scan nested classes should iterate them via IterateRegexCharacterClasses and call ParseRegexCharacterClass on each separately.

type RegexCharElementKind added in v0.15.1

type RegexCharElementKind int

RegexCharElementKind classifies one element of a character class body.

const (
	// RegexCharSingle is a single character element (literal, escape, …).
	RegexCharSingle RegexCharElementKind = iota
	// RegexCharRange is a character range `a-b` (inclusive on both ends).
	// Value is the `a` side; Max is the `b` side. Only the min/max endpoints
	// appear in the resulting character sequence — the inner characters are
	// implicit.
	RegexCharRange
	// RegexCharBreaker is any element that interrupts a contiguous character
	// sequence within a class: `\d`, `\D`, `\w`, `\W`, `\s`, `\S`, `\b`, `\B`,
	// `\p{...}`, `\P{...}`, `\q{...}` (v-flag), nested `[...]` (v-flag), or a
	// v-flag set operator `--` / `&&`.
	RegexCharBreaker
)

type RegexFlags added in v0.15.1

type RegexFlags struct {
	Unicode     bool // u flag
	UnicodeSets bool // v flag
}

RegexFlags captures the subset of ECMAScript regex flags that affects how patterns (and in particular character classes) are parsed.

func ParseRegexFlags added in v0.15.1

func ParseRegexFlags(flags string) RegexFlags

ParseRegexFlags returns a RegexFlags from a flag string (e.g. "gui").

func (RegexFlags) UV added in v0.15.1

func (f RegexFlags) UV() bool

UV reports whether unicode/unicodeSets mode is active (either u or v).

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.

func (*Set[T]) Add

func (s *Set[T]) Add(key T)

func (*Set[T]) Clear

func (s *Set[T]) Clear()

func (*Set[T]) Delete

func (s *Set[T]) Delete(key T)

func (*Set[T]) Has

func (s *Set[T]) Has(key T) bool

func (*Set[T]) Keys

func (s *Set[T]) Keys() map[T]struct{}

func (*Set[T]) Len

func (s *Set[T]) Len() int

type SourceToken added in v0.22.0

type SourceToken struct {
	Kind       ast.Kind
	Start, End int
	Text       string
}

SourceToken is a source-backed token with its kind, byte span, and text.

func PreviousTokenBefore added in v0.22.0

func PreviousTokenBefore(sourceFile *ast.SourceFile, node *ast.Node, pos int) (SourceToken, bool)

PreviousTokenBefore returns the last token in node whose end is not after pos.

func TokenAtOrAfter added in v0.22.0

func TokenAtOrAfter(sourceFile *ast.SourceFile, pos int) (SourceToken, bool)

TokenAtOrAfter returns the first non-trivia token at or after pos.

func TokenBeforePosition added in v0.22.0

func TokenBeforePosition(sourceFile *ast.SourceFile, pos int) (SourceToken, bool)

TokenBeforePosition returns the last non-trivia token whose end is not after pos.

func TokensOfNode added in v0.22.0

func TokensOfNode(sourceFile *ast.SourceFile, node *ast.Node) []SourceToken

TokensOfNode returns all parser tokens contained in node, in source order.

func (SourceToken) Range added in v0.22.0

func (t SourceToken) Range() core.TextRange

Range returns the token's source span.

type StaticStringEvaluator added in v0.22.0

type StaticStringEvaluator struct {
	// contains filtered or unexported fields
}

StaticStringEvaluator folds expressions to string constants. It wraps tsgo's evaluator and adds stable local variable resolution through the TypeChecker. Create one evaluator per linted file; it keeps write-reference and recursion state for that file.

func NewStaticStringEvaluator added in v0.22.0

func NewStaticStringEvaluator(typeChecker *checker.Checker) *StaticStringEvaluator

func NewStaticStringEvaluatorWithSourceFile added in v0.22.0

func NewStaticStringEvaluatorWithSourceFile(typeChecker *checker.Checker, sourceFile *ast.SourceFile) *StaticStringEvaluator

func (*StaticStringEvaluator) Eval added in v0.22.0

func (staticEvaluator *StaticStringEvaluator) Eval(node *ast.Node) (string, bool)

Eval returns the static string value of node, if it can be determined. It covers the string-producing subset of ESLint's getStaticValue that rules use for computed property names, key arguments, constructor arguments, and other string-only rule inputs. It includes nested conditionals, logical short-circuiting, String(), String.raw, and local variables with stable initializers.

func (*StaticStringEvaluator) ResolveIdentifierInitializer added in v0.22.0

func (staticEvaluator *StaticStringEvaluator) ResolveIdentifierInitializer(node *ast.Node) (*ast.Node, bool)

ResolveIdentifierInitializer resolves an identifier to a stable variable initializer: const bindings, or let/var bindings with no write references in the current source file. It returns false for destructuring, using bindings, ambiguous symbols, or files where let/var writes cannot be checked.

type StringCodeUnit added in v0.15.1

type StringCodeUnit struct {
	// Value is the UTF-16 code unit value (0..0xFFFF). For astral entries the
	// two consecutive units carry the high and low surrogate values.
	Value uint32
	// Start is the inclusive byte offset within the literal source text.
	Start int
	// End is the exclusive byte offset within the literal source text.
	End int
}

StringCodeUnit represents one UTF-16 code unit produced by evaluating a JS string literal or no-substitution template literal, paired with the byte range of the source text that produced it.

For most code units one entry maps 1:1 to a slice of the literal's source text. For astral escapes like `\u{1F44D}` and for raw astral characters (4 UTF-8 bytes) two consecutive entries are emitted whose `Start` and `End` are identical — they represent the high and low surrogate halves of the same source span.

Line continuations (`\<LF>`, `\<CR>`, `\<CR><LF>`, `\<LS>`, `\<PS>`) do not produce any code unit.

This mirrors ESLint's `utils/char-source.js` `CodeUnit` class, with the value added so callers don't need to re-parse the source text.

func ParseJSStringLiteralSource added in v0.15.1

func ParseJSStringLiteralSource(source string) []StringCodeUnit

ParseJSStringLiteralSource parses a JS string literal source text (including its surrounding quotes) and returns the per-code-unit source mapping.

Returns nil if the input is not a well-formed string literal prologue (leading quote, closing quote) — the caller should treat this as "give up". The parser is permissive on legacy-octal and identity escapes (matching ESLint's `char-source.js`) and does not enforce strict-mode restrictions.

func ParseJSTemplateLiteralSource added in v0.15.1

func ParseJSTemplateLiteralSource(source string) []StringCodeUnit

ParseJSTemplateLiteralSource parses a no-substitution template literal source (including surrounding backticks) similarly. For templates with substitution `${...}`, pass just one segment at a time is unsupported — callers should treat substituted templates as dynamic.

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

func NeedsToBeAwaited(
	typeChecker *checker.Checker,
	node *ast.Node,
	t *checker.Type,
) TypeAwaitable

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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL