or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.mdlanguage.mdparser.mdquery.mdtree-cursor.mdtree-node.md

parser.mddocs/

0

# Parser

1

2

Core parsing functionality for creating parsers, setting languages, and converting source code into syntax trees. The Parser class is the main entry point for Tree-sitter operations.

3

4

## Capabilities

5

6

### Parser Initialization

7

8

Initialize the WebAssembly module before creating parsers.

9

10

```typescript { .api }

11

/**

12

* Initialize the WebAssembly module. Must be called before creating any Parser instances.

13

* @param moduleOptions - Optional Emscripten module configuration, commonly used to set locateFile for finding the .wasm file

14

* @returns Promise that resolves when WASM module is ready

15

*/

16

static init(moduleOptions?: EmscriptenModule): Promise<void>;

17

```

18

19

**Usage Example:**

20

21

```typescript

22

import { Parser } from "web-tree-sitter";

23

24

// Basic initialization

25

await Parser.init();

26

27

// With custom WASM location

28

await Parser.init({

29

locateFile(scriptName: string, scriptDirectory: string) {

30

return "/custom/path/" + scriptName;

31

}

32

});

33

```

34

35

### Parser Creation

36

37

Create parser instances for parsing operations.

38

39

```typescript { .api }

40

/**

41

* Create a new parser instance

42

*/

43

constructor();

44

45

/**

46

* Delete the parser and free its resources

47

*/

48

delete(): void;

49

```

50

51

### Language Configuration

52

53

Set the parsing language for the parser.

54

55

```typescript { .api }

56

/**

57

* Set the language that the parser should use for parsing

58

* @param language - Language instance or null to unset

59

* @returns Parser instance for chaining

60

* @throws Error if language has incompatible ABI version

61

*/

62

setLanguage(language: Language | null): this;

63

64

/** The parser's current language */

65

language: Language | null;

66

```

67

68

**Usage Example:**

69

70

```typescript

71

import { Parser, Language } from "web-tree-sitter";

72

73

await Parser.init();

74

const parser = new Parser();

75

76

// Load and set JavaScript language

77

const JavaScript = await Language.load("/tree-sitter-javascript.wasm");

78

parser.setLanguage(JavaScript);

79

80

console.log(parser.language?.name); // "javascript"

81

```

82

83

### Parsing Operations

84

85

Parse source code into syntax trees.

86

87

```typescript { .api }

88

/**

89

* Parse source code or use a callback to provide text

90

* @param callback - Source code string or callback function that provides text

91

* @param oldTree - Previous syntax tree for incremental parsing

92

* @param options - Parsing options including ranges and progress callback

93

* @returns Tree if parsing succeeded, null if parser has no language or was cancelled

94

*/

95

parse(callback: string | ParseCallback, oldTree?: Tree | null, options?: ParseOptions): Tree | null;

96

97

/**

98

* Reset parser to start next parse from beginning

99

* Use this when switching to parse a different document after timeout/cancellation

100

*/

101

reset(): void;

102

```

103

104

**Usage Examples:**

105

106

```typescript

107

// Parse source code string

108

const tree = parser.parse("let x = 1 + 2;");

109

110

// Incremental parsing with previous tree

111

const newTree = parser.parse("let x = 1 + 3;", tree);

112

113

// Parse with callback for large documents

114

const largeTree = parser.parse((index, position) => {

115

// Provide text at given byte index and position

116

return getTextAtPosition(index, position);

117

});

118

119

// Parse with options

120

const constrainedTree = parser.parse(sourceCode, null, {

121

includedRanges: [

122

{ startIndex: 0, endIndex: 100, startPosition: {row: 0, column: 0}, endPosition: {row: 5, column: 10} }

123

],

124

progressCallback: (state) => {

125

console.log(`Parsing at offset: ${state.currentOffset}`);

126

// Return to cancel parsing if needed

127

}

128

});

129

```

130

131

### Range Management

132

133

Configure which parts of the document to include during parsing.

134

135

```typescript { .api }

136

/**

137

* Get the ranges of text that the parser will include when parsing

138

* @returns Array of ranges currently set for parsing

139

*/

140

getIncludedRanges(): Range[];

141

```

142

143

### Logging Configuration

144

145

Set up logging for parser operations.

146

147

```typescript { .api }

148

/**

149

* Set the logging callback for parser operations

150

* @param callback - Log callback function, true for console logging, or null to disable

151

* @returns Parser instance for chaining

152

*/

153

setLogger(callback: LogCallback | boolean | null): this;

154

155

/**

156

* Get the parser's current logger

157

* @returns Current log callback or null if not set

158

*/

159

getLogger(): LogCallback | null;

160

```

161

162

**Usage Example:**

163

164

```typescript

165

// Enable console logging

166

parser.setLogger(true);

167

168

// Custom logging

169

parser.setLogger((message, isLex) => {

170

console.log(`[${isLex ? 'LEX' : 'PARSE'}] ${message}`);

171

});

172

173

// Disable logging

174

parser.setLogger(null);

175

```

176

177

### Deprecated Methods

178

179

These methods are deprecated in favor of progress callbacks.

180

181

```typescript { .api }

182

/**

183

* @deprecated Use progressCallback in parse options instead

184

* Get the duration in microseconds that parsing is allowed to take

185

*/

186

getTimeoutMicros(): number;

187

188

/**

189

* @deprecated Use progressCallback in parse options instead

190

* Set the maximum duration in microseconds for parsing

191

*/

192

setTimeoutMicros(timeout: number): void;

193

```

194

195

## Types

196

197

```typescript { .api }

198

interface ParseOptions {

199

/** Array of ranges to include when parsing */

200

includedRanges?: Range[];

201

/** Progress callback for monitoring parsing (void return - different from main ProgressCallback) */

202

progressCallback?: (state: ParseState) => void;

203

}

204

205

interface ParseState {

206

/** Current byte offset in document */

207

currentOffset: number;

208

/** Whether parser has encountered an error */

209

hasError: boolean;

210

}

211

212

/** Callback for providing text during parsing */

213

type ParseCallback = (index: number, position: Point) => string | undefined;

214

215

/** Callback for monitoring parsing progress and optionally cancelling */

216

type ProgressCallback = (progress: ParseState) => boolean;

217

218

/** Callback for logging parser messages */

219

type LogCallback = (message: string, isLex: boolean) => void;

220

221

/** ABI version constants */

222

const LANGUAGE_VERSION: number;

223

const MIN_COMPATIBLE_VERSION: number;

224

```