or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

ast-navigation.mdconfiguration.mdindex.mdparsing.mdprinting.mdserialization.mdsymbol-resolution.mdvisitors.md

configuration.mddocs/

0

# Parser Configuration

1

2

JavaParser provides comprehensive configuration options to control parsing behavior, language level support, symbol resolution, and various parsing features. The ParserConfiguration class centralizes all configuration settings.

3

4

## Capabilities

5

6

### Basic Parser Configuration

7

8

Configure core parsing behavior and language support.

9

10

```java { .api }

11

/**

12

* Configuration class for controlling parser behavior

13

*/

14

public class ParserConfiguration {

15

16

/**

17

* Create configuration with default settings

18

*/

19

public ParserConfiguration();

20

21

/**

22

* Set Java language level to support

23

* @param languageLevel Target Java version

24

* @return This configuration for chaining

25

*/

26

public ParserConfiguration setLanguageLevel(LanguageLevel languageLevel);

27

28

/**

29

* Get current language level

30

* @return Current language level setting

31

*/

32

public LanguageLevel getLanguageLevel();

33

34

/**

35

* Set character encoding for source files

36

* @param characterEncoding Character encoding (e.g., UTF-8)

37

* @return This configuration for chaining

38

*/

39

public ParserConfiguration setCharacterEncoding(Charset characterEncoding);

40

41

/**

42

* Get current character encoding

43

* @return Current character encoding

44

*/

45

public Charset getCharacterEncoding();

46

47

/**

48

* Enable/disable token storage for position tracking

49

* @param storeTokens true to store tokens

50

* @return This configuration for chaining

51

*/

52

public ParserConfiguration setStoreTokens(boolean storeTokens);

53

54

/**

55

* Check if token storage is enabled

56

* @return true if tokens are stored

57

*/

58

public boolean isStoreTokens();

59

60

/**

61

* Set tab width for position calculations

62

* @param tabWidth Number of spaces per tab

63

* @return This configuration for chaining

64

*/

65

public ParserConfiguration setTabWidth(int tabWidth);

66

67

/**

68

* Get tab width setting

69

* @return Current tab width

70

*/

71

public int getTabWidth();

72

}

73

74

/**

75

* Java language level enumeration

76

*/

77

public enum LanguageLevel {

78

/** Java 1.0 support */

79

JAVA_1_0,

80

/** Java 1.1 support */

81

JAVA_1_1,

82

/** Java 1.2 support */

83

JAVA_1_2,

84

/** Java 1.3 support */

85

JAVA_1_3,

86

/** Java 1.4 support */

87

JAVA_1_4,

88

/** Java 5 support (generics, annotations, autoboxing) */

89

JAVA_5,

90

/** Java 6 support */

91

JAVA_6,

92

/** Java 7 support (diamond operator, try-with-resources) */

93

JAVA_7,

94

/** Java 8 support (lambdas, method references, streams) */

95

JAVA_8,

96

/** Java 9 support (modules, private interface methods) */

97

JAVA_9,

98

/** Java 10 support (var keyword) */

99

JAVA_10,

100

/** Java 11 support (var in lambda parameters) */

101

JAVA_11,

102

/** Java 12 support (switch expressions preview) */

103

JAVA_12,

104

/** Java 13 support (text blocks preview) */

105

JAVA_13,

106

/** Java 14 support (switch expressions, records preview) */

107

JAVA_14,

108

/** Java 15 support (text blocks, sealed classes preview) */

109

JAVA_15,

110

/** Java 16 support (records, pattern matching instanceof) */

111

JAVA_16,

112

/** Java 17 support (sealed classes, switch pattern matching) */

113

JAVA_17,

114

/** Java 18 support */

115

JAVA_18,

116

/** Java 19 support */

117

JAVA_19,

118

/** Java 20 support */

119

JAVA_20,

120

/** Java 21 support (virtual threads, pattern matching) */

121

JAVA_21,

122

/** Current/latest supported version */

123

CURRENT

124

}

125

```

126

127

**Usage Examples:**

128

129

```java

130

import com.github.javaparser.ParserConfiguration;

131

import com.github.javaparser.ParserConfiguration.LanguageLevel;

132

import java.nio.charset.StandardCharsets;

133

134

// Configure for Java 17 with UTF-8 encoding

135

ParserConfiguration config = new ParserConfiguration()

136

.setLanguageLevel(LanguageLevel.JAVA_17)

137

.setCharacterEncoding(StandardCharsets.UTF_8)

138

.setStoreTokens(true) // Enable position tracking

139

.setTabWidth(4); // 4 spaces per tab

140

141

// Use configuration with parser

142

JavaParser parser = new JavaParser(config);

143

144

// Parse with specific language level

145

ParseResult<CompilationUnit> result = parser.parse(modernJavaCode);

146

147

// Different configurations for different purposes

148

ParserConfiguration legacyConfig = new ParserConfiguration()

149

.setLanguageLevel(LanguageLevel.JAVA_8); // For older codebases

150

151

ParserConfiguration modernConfig = new ParserConfiguration()

152

.setLanguageLevel(LanguageLevel.JAVA_21) // Latest features

153

.setStoreTokens(true); // For IDE-like features

154

```

155

156

### Symbol Resolution Configuration

157

158

Configure advanced symbol resolution and type analysis capabilities.

159

160

```java { .api }

161

/**

162

* Set symbol resolver for type analysis

163

* @param symbolResolver Symbol resolver implementation

164

* @return This configuration for chaining

165

*/

166

public ParserConfiguration setSymbolResolver(SymbolResolver symbolResolver);

167

168

/**

169

* Get current symbol resolver

170

* @return Current symbol resolver or null if not set

171

*/

172

public Optional<SymbolResolver> getSymbolResolver();

173

174

/**

175

* Check if symbol resolution is enabled

176

* @return true if symbol resolver is configured

177

*/

178

public boolean isSymbolResolutionEnabled();

179

```

180

181

**Usage Examples:**

182

183

```java

184

import com.github.javaparser.symbolsolver.JavaSymbolSolver;

185

import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver;

186

import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver;

187

import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver;

188

189

// Set up symbol resolution

190

CombinedTypeSolver typeSolver = new CombinedTypeSolver();

191

typeSolver.add(new ReflectionTypeSolver()); // JDK classes

192

typeSolver.add(new JavaParserTypeSolver(new File("src/main/java"))); // Project sources

193

194

JavaSymbolSolver symbolResolver = new JavaSymbolSolver(typeSolver);

195

196

// Configure parser with symbol resolution

197

ParserConfiguration config = new ParserConfiguration()

198

.setLanguageLevel(LanguageLevel.JAVA_17)

199

.setSymbolResolver(symbolResolver);

200

201

JavaParser parser = new JavaParser(config);

202

203

// Now parsing enables type resolution

204

CompilationUnit cu = parser.parse(code).getResult().get();

205

206

// Resolve types and symbols

207

for (NameExpr nameExpr : cu.findAll(NameExpr.class)) {

208

try {

209

ResolvedValueDeclaration resolved = nameExpr.resolve();

210

System.out.println("Symbol: " + resolved.getName() + " -> " + resolved.getType());

211

} catch (UnsolvedSymbolException e) {

212

System.out.println("Could not resolve: " + nameExpr.getNameAsString());

213

}

214

}

215

```

216

217

### Validation and Error Handling Configuration

218

219

Configure validation behavior and error handling strategies.

220

221

```java { .api }

222

/**

223

* Set validators for additional syntax and semantic checks

224

* @param validators List of validators to apply

225

* @return This configuration for chaining

226

*/

227

public ParserConfiguration setValidators(List<Validator> validators);

228

229

/**

230

* Get current validators

231

* @return List of configured validators

232

*/

233

public List<Validator> getValidators();

234

235

/**

236

* Add a validator to the configuration

237

* @param validator Validator to add

238

* @return This configuration for chaining

239

*/

240

public ParserConfiguration addValidator(Validator validator);

241

242

/**

243

* Set problem reporter for handling parse problems

244

* @param problemReporter Problem reporter implementation

245

* @return This configuration for chaining

246

*/

247

public ParserConfiguration setProblemReporter(ProblemReporter problemReporter);

248

249

/**

250

* Get current problem reporter

251

* @return Current problem reporter

252

*/

253

public ProblemReporter getProblemReporter();

254

```

255

256

**Usage Examples:**

257

258

```java

259

import com.github.javaparser.ast.validator.*;

260

261

// Configure validation for specific Java version

262

ParserConfiguration config = new ParserConfiguration()

263

.setLanguageLevel(LanguageLevel.JAVA_8);

264

265

// Add custom validators

266

config.addValidator(new ReservedKeywordValidator())

267

.addValidator(new Java8Validator());

268

269

// Custom problem reporter

270

config.setProblemReporter(new ProblemReporter() {

271

@Override

272

public void report(Problem problem) {

273

System.err.println("Parse issue: " + problem.getMessage());

274

if (problem.getLocation().isPresent()) {

275

TokenRange location = problem.getLocation().get();

276

System.err.println("At: " + location.getBegin());

277

}

278

}

279

});

280

281

JavaParser parser = new JavaParser(config);

282

```

283

284

### Preprocessing Configuration

285

286

Configure preprocessing options for source code transformation before parsing.

287

288

```java { .api }

289

/**

290

* Set preprocessing providers for source transformation

291

* @param providers Preprocessing providers

292

* @return This configuration for chaining

293

*/

294

public ParserConfiguration setPreprocessors(List<Processor> providers);

295

296

/**

297

* Add preprocessing provider

298

* @param processor Processor to add

299

* @return This configuration for chaining

300

*/

301

public ParserConfiguration addProcessor(Processor processor);

302

303

/**

304

* Set line ending processing provider

305

* @param provider Line ending processor

306

* @return This configuration for chaining

307

*/

308

public ParserConfiguration setLineEndingProcessingProvider(LineEndingProcessingProvider provider);

309

310

/**

311

* Set unicode escape processing provider

312

* @param provider Unicode escape processor

313

* @return This configuration for chaining

314

*/

315

public ParserConfiguration setUnicodeEscapeProcessingProvider(UnicodeEscapeProcessingProvider provider);

316

```

317

318

**Usage Examples:**

319

320

```java

321

// Configure line ending normalization

322

config.setLineEndingProcessingProvider(

323

LineEndingProcessingProvider.NORMALIZE_TO_LF);

324

325

// Configure unicode escape processing

326

config.setUnicodeEscapeProcessingProvider(

327

UnicodeEscapeProcessingProvider.PROCESS_ESCAPES);

328

329

// Add custom preprocessor

330

config.addProcessor(new Processor() {

331

@Override

332

public String process(String code) {

333

// Custom preprocessing logic

334

return code.replace("//FIXME", "//TODO");

335

}

336

});

337

```

338

339

### Performance and Memory Configuration

340

341

Configure parser performance and memory usage options.

342

343

```java { .api }

344

/**

345

* Set whether to store original tokens for position tracking

346

* @param storeTokens true to store tokens (uses more memory)

347

* @return This configuration for chaining

348

*/

349

public ParserConfiguration setStoreTokens(boolean storeTokens);

350

351

/**

352

* Set whether to perform expensive validation checks

353

* @param performExpensiveChecks true to enable extensive validation

354

* @return This configuration for chaining

355

*/

356

public ParserConfiguration setPerformExpensiveChecks(boolean performExpensiveChecks);

357

358

/**

359

* Set whether to cache parsing results

360

* @param cacheParsingResults true to enable caching

361

* @return This configuration for chaining

362

*/

363

public ParserConfiguration setCacheParsingResults(boolean cacheParsingResults);

364

365

/**

366

* Set maximum parsing depth to prevent stack overflow

367

* @param maxParsingDepth Maximum recursion depth

368

* @return This configuration for chaining

369

*/

370

public ParserConfiguration setMaxParsingDepth(int maxParsingDepth);

371

```

372

373

**Usage Examples:**

374

375

```java

376

// Performance-optimized configuration

377

ParserConfiguration fastConfig = new ParserConfiguration()

378

.setStoreTokens(false) // Save memory

379

.setPerformExpensiveChecks(false) // Skip expensive validation

380

.setCacheParsingResults(true) // Enable caching

381

.setMaxParsingDepth(1000); // Prevent deep recursion

382

383

// Memory-optimized configuration

384

ParserConfiguration memoryConfig = new ParserConfiguration()

385

.setStoreTokens(false) // Don't store tokens

386

.setCacheParsingResults(false); // Don't cache results

387

388

// Full-featured configuration (more memory usage)

389

ParserConfiguration fullConfig = new ParserConfiguration()

390

.setStoreTokens(true) // Store for position tracking

391

.setPerformExpensiveChecks(true) // Full validation

392

.setSymbolResolver(symbolResolver); // Enable type resolution

393

```

394

395

### Configuration Presets

396

397

Common configuration presets for typical use cases.

398

399

```java { .api }

400

/**

401

* Utility methods for common configuration patterns

402

*/

403

public class ParserConfigurationPresets {

404

405

/**

406

* Configuration optimized for IDE features

407

* @return Configuration with full position tracking and symbol resolution

408

*/

409

public static ParserConfiguration ideConfiguration() {

410

return new ParserConfiguration()

411

.setLanguageLevel(LanguageLevel.CURRENT)

412

.setStoreTokens(true)

413

.setPerformExpensiveChecks(true);

414

}

415

416

/**

417

* Configuration optimized for batch processing

418

* @return Lightweight configuration for processing many files

419

*/

420

public static ParserConfiguration batchProcessingConfiguration() {

421

return new ParserConfiguration()

422

.setStoreTokens(false)

423

.setPerformExpensiveChecks(false)

424

.setCacheParsingResults(true);

425

}

426

427

/**

428

* Configuration for legacy Java code

429

* @return Configuration for older Java versions

430

*/

431

public static ParserConfiguration legacyConfiguration() {

432

return new ParserConfiguration()

433

.setLanguageLevel(LanguageLevel.JAVA_8);

434

}

435

436

/**

437

* Configuration for modern Java features

438

* @return Configuration supporting latest Java features

439

*/

440

public static ParserConfiguration modernConfiguration() {

441

return new ParserConfiguration()

442

.setLanguageLevel(LanguageLevel.JAVA_21);

443

}

444

}

445

```

446

447

**Usage Examples:**

448

449

```java

450

// Use preset configurations

451

JavaParser ideParser = new JavaParser(ParserConfigurationPresets.ideConfiguration());

452

JavaParser batchParser = new JavaParser(ParserConfigurationPresets.batchProcessingConfiguration());

453

JavaParser legacyParser = new JavaParser(ParserConfigurationPresets.legacyConfiguration());

454

455

// Customize preset

456

ParserConfiguration customConfig = ParserConfigurationPresets.modernConfiguration()

457

.setCharacterEncoding(StandardCharsets.UTF_8)

458

.setSymbolResolver(mySymbolResolver);

459

```

460

461

### Configuration Builder Pattern

462

463

Fluent builder pattern for complex configuration setup.

464

465

```java { .api }

466

/**

467

* Fluent configuration builder

468

*/

469

public class ParserConfigurationBuilder {

470

471

/**

472

* Start building configuration

473

* @return New builder instance

474

*/

475

public static ParserConfigurationBuilder builder() {

476

return new ParserConfigurationBuilder();

477

}

478

479

/**

480

* Set language level

481

* @param level Java language level

482

* @return This builder for chaining

483

*/

484

public ParserConfigurationBuilder languageLevel(LanguageLevel level) {

485

// Implementation

486

return this;

487

}

488

489

/**

490

* Enable symbol resolution with type solver

491

* @param typeSolver Type solver to use

492

* @return This builder for chaining

493

*/

494

public ParserConfigurationBuilder symbolResolution(TypeSolver typeSolver) {

495

// Implementation

496

return this;

497

}

498

499

/**

500

* Build final configuration

501

* @return Configured ParserConfiguration

502

*/

503

public ParserConfiguration build() {

504

// Implementation

505

return new ParserConfiguration();

506

}

507

}

508

```

509

510

**Usage Examples:**

511

512

```java

513

// Complex configuration with builder

514

ParserConfiguration config = ParserConfigurationBuilder.builder()

515

.languageLevel(LanguageLevel.JAVA_17)

516

.symbolResolution(typeSolver)

517

.encoding(StandardCharsets.UTF_8)

518

.storeTokens(true)

519

.validators(Arrays.asList(

520

new ReservedKeywordValidator(),

521

new Java17Validator()

522

))

523

.problemReporter(customReporter)

524

.build();

525

526

JavaParser parser = new JavaParser(config);

527

```

528

529

## Configuration Validation

530

531

```java { .api }

532

/**

533

* Validate configuration settings

534

* @param config Configuration to validate

535

* @throws IllegalArgumentException if configuration is invalid

536

*/

537

public static void validateConfiguration(ParserConfiguration config);

538

539

/**

540

* Get configuration warnings

541

* @param config Configuration to check

542

* @return List of configuration warnings

543

*/

544

public static List<String> getConfigurationWarnings(ParserConfiguration config);

545

```