0
# AST Utilities
1
2
Utility functions for working with TypeScript and ESTree AST nodes. These utilities provide traversal, inspection, conversion, and compatibility functions for working with both TypeScript and ESTree AST formats.
3
4
## Capabilities
5
6
### AST Traversal
7
8
Simple traversal utilities for walking ESTree-compatible AST nodes with visitor patterns.
9
10
```typescript { .api }
11
/**
12
* Simple AST traversal utility with visitor pattern support
13
* @param startingNode - ESTree node to start traversal from
14
* @param options - Visitor configuration with enter function or specific visitors
15
* @param setParentPointers - Whether to set parent pointers during traversal
16
*/
17
function simpleTraverse(
18
startingNode: TSESTree.Node,
19
options: SimpleTraverseOptions,
20
setParentPointers?: boolean
21
): void;
22
23
/**
24
* Configuration for simple traversal with enter function
25
*/
26
interface SimpleTraverseEnterOptions {
27
enter: (node: TSESTree.Node, parent: TSESTree.Node | undefined) => void;
28
visitorKeys?: Readonly<VisitorKeys>;
29
}
30
31
/**
32
* Configuration for simple traversal with specific node visitors
33
*/
34
interface SimpleTraverseVisitorOptions {
35
visitors: Record<string, (node: TSESTree.Node, parent: TSESTree.Node | undefined) => void>;
36
visitorKeys?: Readonly<VisitorKeys>;
37
}
38
39
type SimpleTraverseOptions = SimpleTraverseEnterOptions | SimpleTraverseVisitorOptions;
40
```
41
42
**Usage Examples:**
43
44
```typescript
45
import { simpleTraverse, parse } from "@typescript-eslint/typescript-estree";
46
47
const ast = parse('const x = 42; function foo() { return x; }');
48
49
// Traverse with enter function
50
simpleTraverse(ast, {
51
enter(node, parent) {
52
console.log(`Visiting ${node.type}`);
53
if (node.type === 'Identifier') {
54
console.log(` Identifier: ${node.name}`);
55
}
56
}
57
});
58
59
// Traverse with specific visitors
60
simpleTraverse(ast, {
61
visitors: {
62
VariableDeclaration(node) {
63
console.log('Found variable declaration');
64
},
65
FunctionDeclaration(node) {
66
console.log(`Found function: ${node.id?.name}`);
67
}
68
}
69
});
70
```
71
72
### Node Inspection Utilities
73
74
Functions for inspecting and analyzing TypeScript AST nodes with version compatibility.
75
76
```typescript { .api }
77
/**
78
* Gets TypeScript modifiers from a node with version compatibility
79
* @param node - TypeScript node to inspect
80
* @param includeIllegalModifiers - Whether to include illegal modifiers
81
* @returns Array of modifier nodes or undefined
82
*/
83
function getModifiers(
84
node: ts.Node | null | undefined,
85
includeIllegalModifiers?: boolean
86
): ts.Modifier[] | undefined;
87
88
/**
89
* Gets TypeScript decorators from a node with version compatibility
90
* @param node - TypeScript node to inspect
91
* @param includeIllegalDecorators - Whether to include illegal decorators
92
* @returns Array of decorator nodes or undefined
93
*/
94
function getDecorators(
95
node: ts.Node | null | undefined,
96
includeIllegalDecorators?: boolean
97
): ts.Decorator[] | undefined;
98
99
/**
100
* Checks if a TypeScript node has a specific modifier
101
* @param modifierKind - TypeScript modifier kind to check for
102
* @param node - TypeScript node to inspect
103
* @returns True if modifier is present
104
*/
105
function hasModifier(modifierKind: ts.KeywordSyntaxKind, node: ts.Node): boolean;
106
107
/**
108
* Gets the last modifier from a TypeScript node
109
* @param node - TypeScript node to inspect
110
* @returns Last modifier or null if none
111
*/
112
function getLastModifier(node: ts.Node): ts.Modifier | null;
113
```
114
115
**Usage Examples:**
116
117
```typescript
118
import { getModifiers, getDecorators, hasModifier } from "@typescript-eslint/typescript-estree";
119
120
// Inspect TypeScript nodes (typically used with parser services)
121
const result = parseAndGenerateServices(code, { project: './tsconfig.json' });
122
const tsNode = result.services.esTreeNodeToTSNodeMap.get(someESTreeNode);
123
124
if (tsNode) {
125
// Get modifiers
126
const modifiers = getModifiers(tsNode);
127
console.log('Modifiers:', modifiers?.map(m => ts.SyntaxKind[m.kind]));
128
129
// Check for specific modifiers
130
const isPublic = hasModifier(ts.SyntaxKind.PublicKeyword, tsNode);
131
const isStatic = hasModifier(ts.SyntaxKind.StaticKeyword, tsNode);
132
133
// Get decorators
134
const decorators = getDecorators(tsNode);
135
console.log('Decorators:', decorators?.length);
136
}
137
```
138
139
### Token and Node Type Utilities
140
141
Functions for working with TypeScript tokens and determining node types.
142
143
```typescript { .api }
144
/**
145
* Gets the string representation of a TypeScript token kind
146
* @param kind - TypeScript SyntaxKind
147
* @returns String representation of the token
148
*/
149
function getTextForTokenKind<T extends ts.SyntaxKind>(kind: T): string | undefined;
150
151
/**
152
* Determines if a TypeScript token is a logical operator
153
* @param operator - Binary operator token
154
* @returns True if logical operator (&&, ||, ??)
155
*/
156
function isLogicalOperator(operator: ts.BinaryOperatorToken): boolean;
157
158
/**
159
* Determines if a TypeScript token is an ESTree binary operator
160
* @param operator - Binary operator token
161
* @returns True if valid ESTree binary operator
162
*/
163
function isESTreeBinaryOperator(operator: ts.BinaryOperatorToken): boolean;
164
165
/**
166
* Gets the binary expression type and operator for a TypeScript token
167
* @param operator - Binary operator token
168
* @returns Object with expression type and operator string
169
*/
170
function getBinaryExpressionType(operator: ts.BinaryOperatorToken): {
171
type: AST_NODE_TYPES.AssignmentExpression | AST_NODE_TYPES.BinaryExpression | AST_NODE_TYPES.LogicalExpression;
172
operator: string;
173
};
174
```
175
176
**Usage Examples:**
177
178
```typescript
179
import {
180
getTextForTokenKind,
181
isLogicalOperator,
182
getBinaryExpressionType
183
} from "@typescript-eslint/typescript-estree";
184
185
// Get token text
186
const plusText = getTextForTokenKind(ts.SyntaxKind.PlusToken); // "+"
187
const equalsText = getTextForTokenKind(ts.SyntaxKind.EqualsToken); // "="
188
189
// Check operator types (used internally during AST conversion)
190
// These would typically be used with TypeScript's AST nodes
191
```
192
193
### Location and Range Utilities
194
195
Functions for working with source locations, ranges, and position information.
196
197
```typescript { .api }
198
/**
199
* Gets line and character information for a position in source file
200
* @param pos - Character position in source
201
* @param ast - TypeScript source file
202
* @returns Position object with line and column (1-based line)
203
*/
204
function getLineAndCharacterFor(pos: number, ast: ts.SourceFile): TSESTree.Position;
205
206
/**
207
* Gets source location information for a range
208
* @param range - Start and end positions
209
* @param ast - TypeScript source file
210
* @returns Source location with start and end positions
211
*/
212
function getLocFor(range: TSESTree.Range, ast: ts.SourceFile): TSESTree.SourceLocation;
213
214
/**
215
* Gets the range (start and end positions) for a TypeScript node
216
* @param node - TypeScript node with getStart and getEnd methods
217
* @param ast - TypeScript source file
218
* @returns Tuple of start and end positions
219
*/
220
function getRange(node: Pick<ts.Node, 'getStart' | 'getEnd'>, ast: ts.SourceFile): [number, number];
221
```
222
223
### Node Classification Utilities
224
225
Functions for classifying and identifying different types of AST nodes.
226
227
```typescript { .api }
228
/**
229
* Determines if a TypeScript node is a valid ESTree class member
230
* @param node - TypeScript node to check
231
* @returns True if valid class member (not semicolon element)
232
*/
233
function isESTreeClassMember(node: ts.Node): boolean;
234
235
/**
236
* Determines if a TypeScript node is a comment
237
* @param node - TypeScript node to check
238
* @returns True if single-line or multi-line comment
239
*/
240
function isComment(node: ts.Node): boolean;
241
242
/**
243
* Determines if a TypeScript node is a JSX token
244
* @param node - TypeScript node to check
245
* @returns True if JSX-related token
246
*/
247
function isJSXToken(node: ts.Node): boolean;
248
249
/**
250
* Determines if a TypeScript node is a computed property name
251
* @param node - TypeScript node to check
252
* @returns True if computed property name
253
*/
254
function isComputedProperty(node: ts.Node): boolean;
255
256
/**
257
* Determines if a node is optional (has question token)
258
* @param node - Node with optional question token
259
* @returns True if has question token
260
*/
261
function isOptional(node: { questionToken?: ts.QuestionToken }): boolean;
262
```
263
264
### Version Compatibility
265
266
Version checking utilities for handling TypeScript version differences.
267
268
```typescript { .api }
269
/**
270
* Object containing boolean flags for TypeScript version compatibility
271
* Versions: 4.7, 4.8, 4.9, 5.0, 5.1, 5.2, 5.3, 5.4
272
*/
273
const typescriptVersionIsAtLeast: Record<
274
'4.7' | '4.8' | '4.9' | '5.0' | '5.1' | '5.2' | '5.3' | '5.4',
275
boolean
276
>;
277
```
278
279
**Usage Examples:**
280
281
```typescript
282
import { typescriptVersionIsAtLeast } from "@typescript-eslint/typescript-estree";
283
284
// Check TypeScript version compatibility
285
if (typescriptVersionIsAtLeast['4.8']) {
286
// Use TypeScript 4.8+ features
287
console.log('TypeScript 4.8+ features available');
288
}
289
290
if (typescriptVersionIsAtLeast['5.3']) {
291
// Use JSDoc parsing mode features
292
console.log('JSDoc parsing mode available');
293
}
294
```
295
296
## Error Handling
297
298
```typescript { .api }
299
/**
300
* Custom error class for TypeScript parsing errors with location information
301
*/
302
class TSError extends Error {
303
constructor(
304
message: string,
305
public readonly fileName: string,
306
public readonly location: {
307
start: { line: number; column: number; offset: number };
308
end: { line: number; column: number; offset: number };
309
}
310
);
311
312
/** Legacy ESLint compatibility property */
313
get index(): number;
314
/** Legacy ESLint compatibility property */
315
get lineNumber(): number;
316
/** Legacy ESLint compatibility property */
317
get column(): number;
318
}
319
320
/**
321
* Creates a TSError with location information
322
* @param message - Error message
323
* @param ast - Source file for location calculation
324
* @param startIndex - Start position of error
325
* @param endIndex - End position of error (defaults to startIndex)
326
* @returns TSError instance with location information
327
*/
328
function createError(
329
message: string,
330
ast: ts.SourceFile,
331
startIndex: number,
332
endIndex?: number
333
): TSError;
334
```
335
336
## Type Definitions
337
338
```typescript { .api }
339
// Position and location types
340
interface Position {
341
line: number;
342
column: number;
343
}
344
345
interface SourceLocation {
346
start: Position;
347
end: Position;
348
}
349
350
type Range = [number, number];
351
352
// Visitor keys for traversal
353
interface VisitorKeys {
354
[nodeType: string]: readonly string[];
355
}
356
357
// Token and node classification types
358
type LogicalOperatorKind =
359
| ts.SyntaxKind.AmpersandAmpersandToken
360
| ts.SyntaxKind.BarBarToken
361
| ts.SyntaxKind.QuestionQuestionToken;
362
363
type BinaryOperatorKind = keyof TSESTree.BinaryOperatorToText;
364
type AssignmentOperatorKind = keyof TSESTree.AssignmentOperatorToText;
365
```