or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

context-management.mdcore-compilation.mdindex.mdinteractive-compilation.mdjava-interfaces.mdplugin-development.mdrepl-scripting.md

java-interfaces.mddocs/

0

# Java Interfaces

1

2

External Java-compatible interfaces for tool integration, reporting, and diagnostics, enabling seamless integration with Java-based build tools, IDEs, and external systems.

3

4

## Capabilities

5

6

### Simple Reporter Interface

7

8

Java interface for handling compiler diagnostics with simple callback-based reporting.

9

10

```scala { .api }

11

/**

12

* Handle compiler diagnostics

13

* Java-compatible interface for receiving compilation messages

14

*/

15

trait SimpleReporter {

16

/**

17

* Report a diagnostic message

18

* Called by the compiler for each diagnostic (error, warning, info)

19

* @param diag Diagnostic information containing message, level, and position

20

*/

21

def report(diag: Diagnostic): Unit

22

}

23

```

24

25

**Usage Examples:**

26

27

```java

28

import dotty.tools.dotc.interfaces.SimpleReporter;

29

import dotty.tools.dotc.interfaces.Diagnostic;

30

31

// Java implementation

32

public class MyReporter implements SimpleReporter {

33

@Override

34

public void report(Diagnostic diag) {

35

System.err.println(

36

diag.level() + ": " + diag.message() +

37

" at " + diag.position().map(p -> p.toString()).orElse("unknown")

38

);

39

}

40

}

41

42

// Usage with compiler

43

Driver driver = new Driver();

44

SimpleReporter reporter = new MyReporter();

45

driver.process(new String[]{"MyFile.scala"}, reporter, null);

46

```

47

48

```scala

49

// Scala implementation

50

import dotty.tools.dotc.interfaces.{SimpleReporter, Diagnostic}

51

52

class ScalaReporter extends SimpleReporter {

53

override def report(diag: Diagnostic): Unit = {

54

val level = diag.level() match {

55

case 0 => "INFO"

56

case 1 => "WARNING"

57

case 2 => "ERROR"

58

case _ => "UNKNOWN"

59

}

60

println(s"[$level] ${diag.message()}")

61

}

62

}

63

```

64

65

### Compiler Callback Interface

66

67

Java interface for receiving compilation events and notifications during the compilation process.

68

69

```scala { .api }

70

/**

71

* React to compilation events

72

* Java-compatible interface for receiving compilation lifecycle callbacks

73

*/

74

trait CompilerCallback {

75

/**

76

* Called when a class file is generated

77

* Provides access to generated bytecode and metadata

78

* @param source Original source file that generated the class

79

* @param generatedClass Generated class file as AbstractFile

80

* @param className Fully qualified name of the generated class

81

*/

82

def onClassGenerated(source: SourceFile, generatedClass: AbstractFile, className: String): Unit = {}

83

84

/**

85

* Called when a source file compilation is completed

86

* Indicates that all phases have been applied to the source file

87

* @param source Source file that was compiled

88

*/

89

def onSourceCompiled(source: SourceFile): Unit = {}

90

91

/**

92

* Called at the start of compilation

93

* Provides opportunity to initialize resources or logging

94

*/

95

def onCompilationStart(): Unit = {}

96

97

/**

98

* Called at the end of compilation

99

* Provides opportunity to clean up resources or perform final reporting

100

* @param success Whether compilation completed successfully

101

*/

102

def onCompilationEnd(success: Boolean): Unit = {}

103

}

104

```

105

106

**Usage Examples:**

107

108

```java

109

import dotty.tools.dotc.interfaces.CompilerCallback;

110

import dotty.tools.dotc.util.SourceFile;

111

import dotty.tools.io.AbstractFile;

112

113

// Java implementation

114

public class BuildToolCallback implements CompilerCallback {

115

@Override

116

public void onClassGenerated(SourceFile source, AbstractFile generatedClass, String className) {

117

System.out.println("Generated class: " + className + " from " + source.path());

118

// Copy to build output directory, update dependency tracking, etc.

119

}

120

121

@Override

122

public void onSourceCompiled(SourceFile source) {

123

System.out.println("Compiled: " + source.path());

124

// Update incremental compilation state

125

}

126

127

@Override

128

public void onCompilationEnd(boolean success) {

129

if (success) {

130

System.out.println("Compilation completed successfully");

131

} else {

132

System.err.println("Compilation failed");

133

}

134

}

135

}

136

```

137

138

```scala

139

// Scala implementation

140

import dotty.tools.dotc.interfaces.CompilerCallback

141

import dotty.tools.dotc.util.SourceFile

142

import dotty.tools.io.AbstractFile

143

144

class IDECallback extends CompilerCallback {

145

override def onClassGenerated(source: SourceFile, generatedClass: AbstractFile, className: String): Unit = {

146

// Notify IDE of new class for indexing

147

println(s"New class available: $className")

148

}

149

150

override def onSourceCompiled(source: SourceFile): Unit = {

151

// Update syntax highlighting, error markers, etc.

152

println(s"Source compiled: ${source.path}")

153

}

154

}

155

```

156

157

### Diagnostic Interface

158

159

Java interface representing compilation diagnostics with position information and severity levels.

160

161

```scala { .api }

162

/**

163

* Represent compilation diagnostics

164

* Java-compatible interface for diagnostic messages with position and severity information

165

*/

166

trait Diagnostic {

167

/**

168

* Get diagnostic severity level

169

* @return Integer representing severity: 0=INFO, 1=WARNING, 2=ERROR

170

*/

171

def level(): Int

172

173

/**

174

* Get diagnostic message text

175

* @return Human-readable diagnostic message

176

*/

177

def message(): String

178

179

/**

180

* Get source position where diagnostic was reported

181

* @return Optional source position, None if position is not available

182

*/

183

def position(): Option[SourcePosition]

184

185

/**

186

* Get diagnostic category/code

187

* @return Optional diagnostic code for programmatic handling

188

*/

189

def code(): Option[String] = None

190

191

/**

192

* Get additional diagnostic information

193

* @return Optional map of additional diagnostic metadata

194

*/

195

def metadata(): java.util.Map[String, String] = java.util.Collections.emptyMap()

196

}

197

```

198

199

### Reporter Result Interface

200

201

Java interface for compilation result information with error counts and status.

202

203

```scala { .api }

204

/**

205

* Result type for reporting operations

206

* Java-compatible interface providing compilation outcome information

207

*/

208

trait ReporterResult {

209

/**

210

* Check if compilation had errors

211

* @return True if any errors were reported during compilation

212

*/

213

def hasErrors(): Boolean

214

215

/**

216

* Check if compilation had warnings

217

* @return True if any warnings were reported during compilation

218

*/

219

def hasWarnings(): Boolean

220

221

/**

222

* Get total number of errors

223

* @return Count of error-level diagnostics

224

*/

225

def errorCount(): Int

226

227

/**

228

* Get total number of warnings

229

* @return Count of warning-level diagnostics

230

*/

231

def warningCount(): Int

232

233

/**

234

* Get all reported diagnostics

235

* @return List of all diagnostics from compilation

236

*/

237

def allDiagnostics(): java.util.List[Diagnostic]

238

}

239

```

240

241

### Source Position Interface

242

243

Java interface for representing positions in source code with line and column information.

244

245

```scala { .api }

246

/**

247

* Position in source code

248

* Java-compatible interface for source location information

249

*/

250

trait SourcePosition {

251

/**

252

* Get source file containing this position

253

* @return Source file reference

254

*/

255

def source(): SourceFile

256

257

/**

258

* Get line number (1-based)

259

* @return Line number where position occurs

260

*/

261

def line(): Int

262

263

/**

264

* Get column number (1-based)

265

* @return Column number where position occurs

266

*/

267

def column(): Int

268

269

/**

270

* Get character offset from start of file

271

* @return Zero-based character offset

272

*/

273

def offset(): Int

274

275

/**

276

* Get end position for range diagnostics

277

* @return Optional end position if this represents a range

278

*/

279

def endOffset(): Option[Int] = None

280

}

281

```

282

283

## Integration Examples

284

285

### Build Tool Integration

286

287

```java

288

// Example Maven/Gradle plugin integration

289

public class ScalaCompilerPlugin {

290

public void compile(List<String> sourceFiles, String outputDir, List<String> classpath) {

291

Driver driver = new Driver();

292

293

SimpleReporter reporter = diagnostic -> {

294

if (diagnostic.level() >= 2) { // ERROR level

295

throw new CompilationException(diagnostic.message());

296

}

297

getLog().warn(diagnostic.message());

298

};

299

300

CompilerCallback callback = new CompilerCallback() {

301

@Override

302

public void onClassGenerated(SourceFile source, AbstractFile generatedClass, String className) {

303

// Copy generated class to Maven/Gradle output directory

304

copyToOutput(generatedClass, outputDir, className);

305

}

306

};

307

308

String[] args = buildCompilerArgs(sourceFiles, outputDir, classpath);

309

ReporterResult result = driver.process(args, reporter, callback);

310

311

if (result.hasErrors()) {

312

throw new CompilationException("Compilation failed with " + result.errorCount() + " errors");

313

}

314

}

315

}

316

```

317

318

### IDE Integration

319

320

```java

321

// Example IDE language server integration

322

public class ScalaLanguageServer {

323

private Driver driver = new Driver();

324

325

public void handleDidChange(String filePath, String content) {

326

SimpleReporter reporter = diagnostic -> {

327

// Send diagnostic to IDE client

328

sendDiagnostic(filePath, diagnostic);

329

};

330

331

// Compile updated file

332

String[] args = {filePath, "-classpath", getProjectClasspath()};

333

driver.process(args, reporter, null);

334

}

335

336

private void sendDiagnostic(String filePath, Diagnostic diagnostic) {

337

JsonObject lspDiagnostic = new JsonObject();

338

lspDiagnostic.addProperty("message", diagnostic.message());

339

lspDiagnostic.addProperty("severity", mapSeverity(diagnostic.level()));

340

341

diagnostic.position().ifPresent(pos -> {

342

JsonObject range = new JsonObject();

343

range.addProperty("line", pos.line() - 1); // LSP uses 0-based

344

range.addProperty("character", pos.column() - 1);

345

lspDiagnostic.add("range", range);

346

});

347

348

// Send to IDE client via LSP protocol

349

sendToClient(filePath, lspDiagnostic);

350

}

351

}

352

```

353

354

## Types

355

356

### AbstractFile

357

358

```scala { .api }

359

/**

360

* Abstract file representation used throughout the compiler

361

*/

362

abstract class AbstractFile {

363

def name: String

364

def path: String

365

def isDirectory: Boolean

366

def exists: Boolean

367

def lastModified: Long

368

}

369

```

370

371

### SourceFile

372

373

```scala { .api }

374

/**

375

* Source file with content and metadata

376

*/

377

class SourceFile {

378

def file: AbstractFile

379

def content: Array[Char]

380

def path: String

381

def lineIndices: Array[Int]

382

}

383

```