or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

code-generation.mdindex.mdminification.mdparsing.mdtransformation.md

parsing.mddocs/

0

# Code Parsing

1

2

Parse JavaScript and TypeScript source code into Abstract Syntax Trees (AST) with comprehensive syntax support, error reporting, and configurable parser options.

3

4

## Capabilities

5

6

### Parse Function (Async)

7

8

Parses source code into an AST asynchronously, returning a Module by default or Script for non-module code.

9

10

```typescript { .api }

11

/**

12

* Parse source code into an AST asynchronously

13

* @param src - Source code string to parse

14

* @param options - Parser configuration options

15

* @returns Promise resolving to Module AST

16

*/

17

function parse(src: string, options?: ParseOptions): Promise<Module>;

18

19

/**

20

* Parse source code into a Script AST asynchronously

21

* @param src - Source code string to parse

22

* @param options - Parser configuration with isModule set to false or "commonjs"

23

* @returns Promise resolving to Script AST

24

*/

25

function parse(src: string, options: ParseOptions & { isModule: false | "commonjs" }): Promise<Script>;

26

```

27

28

**Usage Examples:**

29

30

```typescript

31

import * as swc from "@swc/wasm";

32

33

// Parse TypeScript code

34

const ast = await swc.parse(`

35

interface User {

36

name: string;

37

age: number;

38

}

39

40

const user: User = { name: "Alice", age: 25 };

41

`, {

42

syntax: "typescript",

43

target: "es2020"

44

});

45

46

// Parse JavaScript with JSX

47

const jsxAst = await swc.parse(`

48

function Component() {

49

return <div>Hello World</div>;

50

}

51

`, {

52

syntax: "ecmascript",

53

jsx: true,

54

target: "es2018"

55

});

56

57

// Parse as Script (non-module)

58

const scriptAst = await swc.parse(`

59

var x = 1;

60

function foo() { return x; }

61

`, {

62

syntax: "ecmascript",

63

isModule: false

64

});

65

```

66

67

### Parse Sync Function

68

69

Parses source code into an AST synchronously with identical interface to async version.

70

71

```typescript { .api }

72

/**

73

* Parse source code into an AST synchronously

74

* @param src - Source code string to parse

75

* @param options - Parser configuration options

76

* @returns Module AST

77

*/

78

function parseSync(src: string, options?: ParseOptions): Module;

79

80

/**

81

* Parse source code into a Script AST synchronously

82

* @param src - Source code string to parse

83

* @param options - Parser configuration with isModule set to false or "commonjs"

84

* @returns Script AST

85

*/

86

function parseSync(src: string, options: ParseOptions & { isModule: false | "commonjs" }): Script;

87

```

88

89

**Usage Examples:**

90

91

```typescript

92

import * as swc from "@swc/wasm";

93

94

// Synchronous parsing

95

const ast = swc.parseSync(`class Example {}`, {

96

syntax: "typescript",

97

target: "es2021"

98

});

99

100

// Parse with comments preserved

101

const astWithComments = swc.parseSync(`

102

// This is a comment

103

const value = 42;

104

`, {

105

syntax: "ecmascript",

106

comments: true

107

});

108

```

109

110

## Configuration Types

111

112

### ParseOptions Interface

113

114

```typescript { .api }

115

interface ParseOptions extends ParserConfig {

116

/** Include comments in the AST */

117

comments?: boolean;

118

/** Parse as script instead of module */

119

script?: boolean;

120

/** Compilation target for syntax validation */

121

target?: JscTarget;

122

}

123

```

124

125

### Parser Configuration

126

127

```typescript { .api }

128

type ParserConfig = TsParserConfig | EsParserConfig;

129

130

interface TsParserConfig {

131

/** Parser syntax type */

132

syntax: "typescript";

133

/** Enable TSX/JSX parsing */

134

tsx?: boolean;

135

/** Enable decorator syntax */

136

decorators?: boolean;

137

/** Enable dynamic import syntax */

138

dynamicImport?: boolean;

139

}

140

141

interface EsParserConfig {

142

/** Parser syntax type */

143

syntax: "ecmascript";

144

/** Enable JSX parsing */

145

jsx?: boolean;

146

/** Enable function bind operator */

147

functionBind?: boolean;

148

/** Enable decorator syntax */

149

decorators?: boolean;

150

/** Allow decorators before export */

151

decoratorsBeforeExport?: boolean;

152

/** Enable export default from syntax */

153

exportDefaultFrom?: boolean;

154

/** Enable import assertions */

155

importAssertions?: boolean;

156

}

157

```

158

159

## AST Node Types

160

161

### Program Types

162

163

```typescript { .api }

164

type Program = Module | Script;

165

166

interface Module extends Node, HasSpan {

167

type: "Module";

168

body: ModuleItem[];

169

interpreter: string;

170

}

171

172

interface Script extends Node, HasSpan {

173

type: "Script";

174

body: Statement[];

175

interpreter: string;

176

}

177

178

type ModuleItem = ModuleDeclaration | Statement;

179

```

180

181

### Base Node Interfaces

182

183

```typescript { .api }

184

interface Node {

185

type: string;

186

}

187

188

interface HasSpan {

189

span: Span;

190

}

191

192

interface Span {

193

start: number;

194

end: number;

195

ctxt: number;

196

}

197

```

198

199

### Statement Types

200

201

```typescript { .api }

202

type Statement =

203

| BlockStatement

204

| EmptyStatement

205

| DebuggerStatement

206

| WithStatement

207

| ReturnStatement

208

| LabeledStatement

209

| BreakStatement

210

| ContinueStatement

211

| IfStatement

212

| SwitchStatement

213

| ThrowStatement

214

| TryStatement

215

| WhileStatement

216

| DoWhileStatement

217

| ForStatement

218

| ForInStatement

219

| ForOfStatement

220

| Declaration

221

| ExpressionStatement;

222

```

223

224

### Expression Types

225

226

```typescript { .api }

227

type Expression =

228

| ThisExpression

229

| ArrayExpression

230

| ObjectExpression

231

| FunctionExpression

232

| UnaryExpression

233

| UpdateExpression

234

| BinaryExpression

235

| AssignmentExpression

236

| MemberExpression

237

| SuperPropExpression

238

| ConditionalExpression

239

| CallExpression

240

| NewExpression

241

| SequenceExpression

242

| Identifier

243

| Literal

244

| TemplateLiteral

245

| TaggedTemplateExpression

246

| ArrowFunctionExpression

247

| ClassExpression

248

| YieldExpression

249

| MetaProperty

250

| AwaitExpression

251

| ParenthesisExpression

252

| JSXElement

253

| JSXFragment

254

| TsTypeAssertion

255

| TsConstAssertion

256

| TsNonNullExpression

257

| TsAsExpression

258

| TsInstantiation

259

| PrivateName

260

| OptionalChainingExpression

261

| Invalid;

262

```

263

264

## Error Handling

265

266

Parse functions throw JavaScript Error objects for syntax errors with detailed position information:

267

268

- **Error Type**: JavaScript `Error`

269

- **Error Message**: "Syntax Error" with detailed description

270

- **Error Details**: Specific expectation messages like "Expected ';', '}' or <eof>"

271

272

**Example Error Handling:**

273

274

```typescript

275

try {

276

const ast = await swc.parse("invalid syntax {}", {

277

syntax: "ecmascript"

278

});

279

} catch (error) {

280

console.error("Parse Error:", error.message);

281

// Output: "Syntax Error: Expected ';', '}' or <eof>"

282

}

283

```