Skip to main content
Version: Next

Serialize the AST

The CLI can export JSON or XML via the parse command (see Usage). From library code you can serialize the AST the same way — useful for golden tests, feeding external tools, or caching parse results.

Add Dependencies​

repositories {
mavenLocal()
mavenCentral()
flatDir {
dirs("deps")
}
}

dependencies {
implementation(files("deps/clparser-with-dependencies-1.0.1-all.jar"))
}

Export JSON​

Kolasu provides JsonGenerator to write the full AST tree, including node types and properties discovered by introspection. This is the same mechanism used by the CLI.

import com.strumenta.cl.parser.CLKolasuParser
import com.strumenta.kolasu.commercial.LicenseManager
import com.strumenta.kolasu.serialization.JsonGenerator
import java.io.File

fun exportJson(clFile: File, license: File, outputJson: File) {
LicenseManager.registerLicense(license)
val result = CLKolasuParser().parse(clFile)
if (result.root == null) {
error("No AST for ${clFile.name}")
}

val json = JsonGenerator().generateString(result, null)
outputJson.writeText(json)
println("Wrote ${outputJson.absolutePath}")
}

The JSON format matches what the CLI parse -f json command writes. You can load it into the interactive AST viewer by placing files under static/parser-examples/.

Export XML​

For tools that prefer XML, use XMLGenerator with the same API (matching the CLI -f xml option):

import com.strumenta.kolasu.serialization.XMLGenerator

fun exportXml(result: com.strumenta.kolasu.parsing.ParsingResult<*>, outputXml: File) {
val xml = XMLGenerator().generateString(result.toResult())
outputXml.writeText(xml)
}

Serialize when you need a snapshot for storage, diffing, or non-JVM consumers. Walk when you need structured extraction (inventory, call sites, file operations) without persisting the entire tree.