lean4-tree-sitter: Parse Any Language from Lean 4

When you're building tools that need to understand source code in other languages, you have two options: write your own parser, or use someone else's. Tree-sitter is the gold standard for incremental parsing across dozens of languages, powering editors like Neovim, Helix, and Zed. But if your tooling is written in Lean 4, there was no way to use it. You'd be stuck rolling your own parser or shelling out to an external process and hoping the output stayed stable.

We needed tree-sitter from inside Lean 4. So we built the bindings.

lean4-tree-sitter is a Lean 4 library that wraps tree-sitter's C API, provides typed grammar specifications for multiple languages, and includes a generic extraction engine that turns source code into structured declarations. On top of that, it ships with kernel-checked proofs about the correctness of its mappings.

What it does

The library is organized into six modules, each handling a different concern:

  • TreeSitter.FFI — Safe Lean 4 wrappers around tree-sitter's C API: parser, tree, node, and query.
  • TreeSitter.Types — Core data structures for declarations, source locations, and extraction results.
  • TreeSitter.Grammars — Typed inductive types for each supported language's node kinds, with a GrammarSpec typeclass that carries proof obligations.
  • TreeSitter.Extract — A generic declaration extraction engine that produces typed Declaration arrays with source locations and nested children.
  • TreeSitter.SourceMap — Bidirectional mapping between source locations in the original language and generated Lean 4 code, with lookup and error tracing.
  • TreeSitter.Proofs — Kernel-checked proofs of mapping totality, cross-language consistency, and source map correctness.

Here's what parsing looks like:

import TreeSitter
open TreeSitter
open TreeSitter.FFI

def example : IO Unit := do
  let parser ← TSParser.new
  let lang ← treeSitterJava
  let _ ← parser.setLanguage lang
  let tree ← parser.parseString "public class Hello { }"
  let root ← tree.rootNode
  let rootType ← root.type
  IO.println s!"Root node type: {rootType}"

That gives you access to tree-sitter's full parse tree. But for most use cases, you don't want to walk nodes manually. The extraction engine does the heavy lifting:

def extractExample : IO Unit := do
  let decls ← extractJava "public class UserService { public void run() {} }"
  for d in decls do
    IO.println s!"{d.name} ({repr d.declType}) at line {d.source.startLine}"

This produces typed Declaration values with names, declaration types, source locations, and nested children, all extracted automatically from the parse tree.

Supported languages

The library currently ships grammars and extraction support for three languages:

LanguageParserExtracted declarations
Javatree-sitter-javaclass, interface, enum, method, field
Pythontree-sitter-pythonclass, function
Kotlintree-sitter-kotlinclass, function, property, type alias

Each grammar is modeled as a typed inductive type with a GrammarSpec instance. Adding a new language means defining its node types and implementing the spec, the extraction engine handles the rest generically.

Why we built it

At Predictable Machines, we're building tools that translate code from other languages into verified Lean 4 programs. To do that well, we need to parse source code structurally, not with string manipulation or regex, but with a real parser that understands the syntax of each language.

Tree-sitter was the obvious choice. It's battle-tested, supports every language we care about, and produces concrete syntax trees that are easy to traverse. What was missing was a way to use it from Lean 4 with proper types and the kind of correctness guarantees we expect from everything in our stack.

The GrammarSpec typeclass, for example, doesn't just describe a language's node types. It carries proof obligations about the completeness of the mapping: every node kind the parser can produce must be accounted for in the grammar's inductive type. The proofs in TreeSitter.Proofs go further, verifying cross-language consistency and source map correctness at the kernel level.

Source maps

One feature worth calling out is the source map module. When you transform code from one language to Lean 4, error messages and debugging information need to point back to the original source. TreeSitter.SourceMap provides bidirectional mappings between locations in the source language and the generated Lean 4 code, so you can trace errors back to the line that caused them.

This isn't just convenience. When a formal verification tool reports that a proof obligation failed at a certain location in the generated Lean code, you need to know which line of the original Java or Python code is responsible. Source maps make that tractable.

Getting started

Head over to the lean4-tree-sitter GitHub repo for up to date installation and usage instructions. The short version:

-- lakefile.lean
require «tree-sitter» from git
  "https://github.com/predictable-machines/lean4-tree-sitter" @ "v0.1.0"

You'll need a C compiler for the FFI layer, but beyond that it's a standard Lake dependency.

What's next

We're actively adding support for more languages as we need them. The architecture is designed to make this straightforward: define the grammar types, implement GrammarSpec, and the extraction engine picks it up.

We'd also like to expand the proof coverage, particularly around the extraction logic, and improve the source map API based on real-world usage.

If you're building developer tools in Lean 4, or you're interested in how typed FFI bindings and formal verification can work together in practice, give it a try. Issues and PRs are welcome on GitHub.

At Predictable Machines, we believe the tools we use to build correct software should themselves be correct. lean4-tree-sitter is one more step toward that goal, and part of a growing collection of libraries we're releasing. Check out lean4-json-schema, our library for JSON Schema with machine-checked correctness proofs, and lean4-markdown, our typed Markdown generation library. To stay up to date with all our open-source projects, visit our Open Source page.

Want to learn how we use Lean 4 and formal verification to prove your code is correct? Learn more about Predictable Code.

What we're building

Predictable Code gives every developer and AI assistant the same shared specifications so the code generated is consistent, verified, and always aligned with what your team intended.

Join the beta

Series

This article is part of our ongoing series on the hidden problems with AI code assistants in engineering teams.

Read the AI Code Pain Points →

More Articles

All articles

/ Curious to see our products in action? \

Let's have a chat about it

Predictable Code